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

if [ "$#" -lt 1 ]; then
  echo "usage: with-env <dev|staging> -- <command> [args...]" >&2
  exit 2
fi

ENVIRONMENT="$1"
shift
[ "${1:-}" = "--" ] && shift
[ "$#" -gt 0 ] || { echo "with-env: no command given" >&2; exit 2; }

case "$ENVIRONMENT" in dev|staging) ;; *) echo "with-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
  export WITH_ENV_SOURCE=ci WITH_ENV_ENVIRONMENT="$ENVIRONMENT" WITH_ENV_STATE_FILE="$STATE_FILE"
  exec "$@"
fi

command -v infisical >/dev/null 2>&1 || {
  echo "with-env: install Infisical, run 'infisical login', and link this repo with 'infisical init'." >&2
  exit 1
}
[ -f "$ROOT_DIR/.infisical.json" ] || { echo "with-env: .infisical.json is missing." >&2; exit 1; }

TMP_ENV="$(mktemp "${TMPDIR:-/tmp}/spoon-$ENVIRONMENT.XXXXXX.env")"
trap 'rm -f "$TMP_ENV"' EXIT INT TERM HUP
sh "$ROOT_DIR/scripts/export-env" "$ENVIRONMENT" > "$TMP_ENV"

export WITH_ENV_SOURCE=infisical WITH_ENV_ENVIRONMENT="$ENVIRONMENT" WITH_ENV_STATE_FILE="$STATE_FILE"
set +e
bunx dotenv -e "$TMP_ENV" -- "$@"
status=$?
set -e
exit "$status"
