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

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

uploaded=0
garage_configured=0

if [[ -n "${BURROW_GARAGE_ENDPOINT:-}" && -n "${AWS_ACCESS_KEY_ID:-}" && -n "${AWS_SECRET_ACCESS_KEY:-}" ]]; then
  garage_configured=1
fi

if [[ "$garage_configured" == "1" ]]; then
  Scripts/ci/upload-package-garage.sh
  uploaded=1
elif [[ "${BURROW_PACKAGE_REQUIRE_GARAGE:-false}" == "true" ]]; then
  echo "Garage package repository upload is required, but BURROW_GARAGE_ENDPOINT or AWS credentials are missing" >&2
  exit 1
else
  echo "::notice ::Garage package repository upload not configured; skipping primary S3-compatible target."
fi

if [[ "${BURROW_PACKAGE_GCS_BACKUP:-true}" != "false" ]]; then
  if ! command -v gcloud >/dev/null 2>&1; then
    echo "gcloud is required for GCS package repository backup" >&2
    exit 127
  fi
  if ! gcloud auth list --filter=status:ACTIVE --format='value(account)' | grep -q .; then
    Scripts/ci/google-wif-auth.sh
  fi
  Scripts/ci/upload-package-repositories.sh
  uploaded=1
fi

if [[ "$uploaded" != "1" ]]; then
  echo "no package repository storage targets were enabled" >&2
  exit 1
fi
