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

: "${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_PACKAGE_REPOSITORY_DIR:-${repo_root}/publish/repositories}"

if [[ ! -d "$source_dir" ]]; then
  echo "package repository 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 package repository upload" >&2
  exit 127
fi

bucket="${BURROW_PACKAGE_GARAGE_BUCKET:-burrow-packages}"
prefix="${BURROW_PACKAGE_GARAGE_PREFIX:-${BURROW_PACKAGE_GCS_PREFIX:-}}"
region="${BURROW_GARAGE_REGION:-garage}"
destination="s3://${bucket}"

if [[ -n "$prefix" ]]; then
  destination="${destination}/${prefix}"
fi

export AWS_DEFAULT_REGION="$region"
export AWS_EC2_METADATA_DISABLED=true

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