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

usage() {
  cat <<'EOF'
Usage:
  AI_GATEWAY_ACCEPTANCE_SNAPSHOT_DATABASE_URL='postgresql://...' \
    scripts/acceptance/export-production-snapshot.sh \
      --release-sha <full-sha> --output <snapshot.json>

This command is database read-only. The supplied role should have SELECT access
only. It never prints the database URL or candidate credentials.
EOF
}

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

[[ ${1:-} == --release-sha && ${3:-} == --output && $# -eq 4 ]] || {
  usage >&2
  exit 64
}
release_sha=$2
output=$4
database_url=${AI_GATEWAY_ACCEPTANCE_SNAPSHOT_DATABASE_URL:-}

[[ $release_sha =~ ^[0-9a-f]{40}$ ]] || {
  echo 'release SHA must be a full lowercase Git SHA' >&2
  exit 64
}
[[ -n $database_url ]] || {
  echo 'AI_GATEWAY_ACCEPTANCE_SNAPSHOT_DATABASE_URL is required' >&2
  exit 64
}
umask 077
(
  cd "$repository_root/apps/api"
  AI_GATEWAY_DATABASE_URL="$database_url" \
    go run ./cmd/acceptance-snapshot export \
      --release-sha "$release_sha" \
      --output "$output"
)
chmod 0600 "$output"
