#!/usr/bin/env bash
set -euo pipefail

: "${BUILD_NUMBER:?BUILD_NUMBER is required}"
: "${BURROW_GARAGE_ENDPOINT:?BURROW_GARAGE_ENDPOINT is required}"
: "${AWS_ACCESS_KEY_ID:?AWS_ACCESS_KEY_ID is required for Garage upload}"
: "${AWS_SECRET_ACCESS_KEY:?AWS_SECRET_ACCESS_KEY is required for Garage upload}"

repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "${repo_root}"

source_dir="${BURROW_RELEASE_OUT:-${repo_root}/dist/builds/${BUILD_NUMBER}}"

if [[ ! -d "$source_dir" ]]; then
  echo "release artifact directory not found: $source_dir" >&2
  exit 1
fi

if ! command -v aws >/dev/null 2>&1; then
  echo "aws CLI is required for Garage release upload" >&2
  exit 127
fi

bucket="${BURROW_RELEASE_GARAGE_BUCKET:-burrow-releases}"
region="${BURROW_GARAGE_REGION:-garage}"
destination="s3://${bucket}/builds/${BUILD_NUMBER}"

export AWS_DEFAULT_REGION="$region"
export AWS_EC2_METADATA_DISABLED=true

aws --endpoint-url "$BURROW_GARAGE_ENDPOINT" s3 sync "$source_dir" "$destination" --no-progress
