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

if ! command -v gh >/dev/null 2>&1; then
  echo "GitHub CLI (gh) is required. Install it and authenticate with 'gh auth login'." >&2
  exit 1
fi

if ! gh auth status >/dev/null 2>&1; then
  echo "Run 'gh auth login' before executing this script." >&2
  exit 1
fi

detect_repo() {
  if [[ -n "${GITHUB_REPOSITORY:-}" ]]; then
    echo "$GITHUB_REPOSITORY"
    return
  fi
  local remote
  remote=$(git config --get remote.origin.url 2>/dev/null || true)
  if [[ -z "$remote" ]]; then
    echo "Unable to determine git remote. Set GITHUB_REPOSITORY=owner/repo." >&2
    exit 1
  fi
  remote=${remote%.git}
  remote=${remote#git@github.com:}
  remote=${remote#https://github.com/}
  echo "$remote"
}

REPO=$(detect_repo)
echo "Using repository: $REPO"

encode_file() {
  local file="$1"
  if base64 --help 2>&1 | grep -q -- '--wrap'; then
    base64 --wrap=0 < "$file"
  else
    base64 < "$file" | tr -d '\n'
  fi
}

set_secret_from_file() {
  local secret="$1"
  local file="$2"
  if [[ ! -f "$file" ]]; then
    echo "Skipping missing $file (secret $secret)" >&2
    return
  fi
  echo "Syncing $secret from $file"
  encode_file "$file" | gh secret set "$secret" --repo "$REPO" --body -
}

set_secret_from_tar_dir() {
  local secret="$1"
  local dir="$2"
  if [[ ! -d "$dir" ]]; then
    echo "Skipping missing directory $dir (secret $secret)" >&2
    return
  fi
  echo "Syncing $secret from directory $dir"
  local tmp
  tmp=$(mktemp)
  tar -czf "$tmp" -C "$(dirname "$dir")" "$(basename "$dir")"
  encode_file "$tmp" | gh secret set "$secret" --repo "$REPO" --body -
  rm -f "$tmp"
}

SECRET_FILE_MAP=(
  "ENV_ROOT_B64=.env"
  "ENV_ROOT_DEV_B64=.env.development"
  "ENV_PRODUCTION_B64=.env.production"
  "ENV_API_B64=apps/api/.env"
  "ENV_WEB_B64=apps/web/.env"
  "SERVICE_ACCOUNT_B64=serviceAccount.json"
)

for entry in "${SECRET_FILE_MAP[@]}"; do
  secret="${entry%%=*}"
  file="${entry#*=}"
  set_secret_from_file "$secret" "$file"
done

set_secret_from_tar_dir "FIREBASE_TAR_B64" "firebase"

echo "Secrets synchronized to GitHub."
