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

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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
STATE_FILE="$ROOT_DIR/.local/$ENVIRONMENT.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; }

(cd "$ROOT_DIR" && infisical export --env="$ENVIRONMENT" --format=dotenv --silent) || {
  echo "export-env: failed to export '$ENVIRONMENT'; check login and project access." >&2
  exit 1
}

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
