#!/usr/bin/env sh
set -eu

[ "$#" -eq 1 ] || { echo "usage: export-env <dev|staging|production|prod>" >&2; exit 2; }
ENVIRONMENT="$1"
case "$ENVIRONMENT" in
  dev|staging|production|prod) ;;
  *) echo "export-env: expected dev, staging, production, or prod" >&2; exit 2 ;;
esac
INFISICAL_ENV="$ENVIRONMENT"
case "$INFISICAL_ENV" in
  production) INFISICAL_ENV=prod ;;
esac

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
STATE_FILE="$ROOT_DIR/.local/$INFISICAL_ENV.generated.env"

if [ -n "${CI:-}" ]; then
  echo "export-env: refusing to export secrets in CI; use injected variables or CI_ENV_FILE." >&2
  exit 1
fi

[ -f "$ROOT_DIR/.infisical.json" ] || { echo "export-env: run 'infisical init' in this repository." >&2; exit 1; }
command -v infisical >/dev/null 2>&1 || { echo "export-env: Infisical CLI is required." >&2; exit 1; }
"$ROOT_DIR/scripts/infisical-account" ensure

# Retry transient Infisical failures (e.g. 500s when several dev tasks fetch
# concurrently at startup) so one flaky response doesn't kill the dev server.
attempt=0
while :; do
  attempt=$((attempt + 1))
  if EXPORT_OUT=$(cd "$ROOT_DIR" && infisical export --env="$INFISICAL_ENV" --format=dotenv --silent 2>"/tmp/export-env.$$.err"); then
    printf '%s\n' "$EXPORT_OUT"
    break
  fi
  if [ "$attempt" -ge 5 ]; then
    cat "/tmp/export-env.$$.err" >&2 2>/dev/null || true
    rm -f "/tmp/export-env.$$.err"
    echo "export-env: failed to export '$INFISICAL_ENV' after $attempt attempts; check login and project access." >&2
    exit 1
  fi
  echo "export-env: Infisical export failed (attempt $attempt/5), retrying in 2s..." >&2
  sleep 2
done
rm -f "/tmp/export-env.$$.err"

if [ -f "$STATE_FILE" ]; then
  printf '\n'
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in ''|'#'*) printf '%s\n' "$line"; continue ;; esac
    key=${line%%=*}
    value=${line#*=}
    case "$value" in \'*\') value=${value#\'}; value=${value%\'} ;; \"*\") value=${value#\"}; value=${value%\"} ;; esac
    escaped=$(printf '%s' "$value" | sed "s/'/'\\\\''/g")
    printf "%s='%s'\n" "$key" "$escaped"
  done < "$STATE_FILE"
fi
