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

usage() {
  cat <<'EOF'
Usage:
  AI_GATEWAY_ACCESS_RULE_AUDIT_DATABASE_URL='postgresql://...' \
    scripts/acceptance/export-access-rule-audit.sh export --output <before.json>

  AI_GATEWAY_ACCESS_RULE_AUDIT_DATABASE_URL='postgresql://...' \
    scripts/acceptance/export-access-rule-audit.sh verify \
      --before <before.json> --output <after.json>

Use a SELECT-only database role. The output contains grouped counts and
SHA-256 digests only; API Key secrets and subject/resource identifiers are not
exported.
EOF
}

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

[[ $# -ge 1 ]] || {
  usage >&2
  exit 64
}
[[ -n ${AI_GATEWAY_ACCESS_RULE_AUDIT_DATABASE_URL:-} ]] || {
  echo 'AI_GATEWAY_ACCESS_RULE_AUDIT_DATABASE_URL is required' >&2
  exit 64
}

case $1 in
  export)
    [[ ${2:-} == --output && $# -eq 3 ]] || {
      usage >&2
      exit 64
    }
    ;;
  verify)
    [[ ${2:-} == --before && ${4:-} == --output && $# -eq 5 ]] || {
      usage >&2
      exit 64
    }
    ;;
  *)
    usage >&2
    exit 64
    ;;
esac

umask 077
(
  cd "$repository_root/apps/api"
  go run ./cmd/access-rule-audit "$@"
)
