#!/usr/bin/env bash
# sops-env — wrapper around SOPS for this repo's .env.sops file.
# Injects decrypted values into the child's environment via `sops exec-env`:
# no temp file ever exists and values are imported verbatim, never evaluated
# by a shell. Plaintext never touches any disk.
#
# Usage:
#   scripts/sops-env <command>           # run command with secrets in env
#   scripts/sops-env decrypt             # print decrypted env to stdout
#   scripts/sops-env edit                # edit encrypted file in place
#
# Requires: ~/bin/sops; ~/.config/sops/age/keys.txt or SOPS_AGE_KEY env var.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# The encrypted file is named .sops.env (NOT .env.sops): `sops exec-env`
# infers the dotenv format from a trailing .env and has no --input-type
# option of its own, so the estate's usual .env.sops name would be parsed
# as JSON and fail. The .env.sops spelling is still honored as a fallback
# for decrypt/edit compatibility with older checkouts.
ENV_FILE="${SOPS_ENV_FILE:-$REPO_ROOT/.sops.env}"
if [ ! -f "$ENV_FILE" ] && [ -f "$REPO_ROOT/.env.sops" ]; then
  ENV_FILE="$REPO_ROOT/.env.sops"
fi

if [ ! -f "$ENV_FILE" ]; then
  echo "sops-env: no encrypted env file at $ENV_FILE" >&2
  exit 2
fi

if [ -x "$HOME/bin/sops" ]; then
  SOPS_BIN="$HOME/bin/sops"
elif command -v sops >/dev/null 2>&1; then
  SOPS_BIN="sops"
else
  echo "sops-env: sops binary not found (tried ~/bin/sops and PATH)" >&2
  exit 3
fi

decrypt_to_stdout() {
  exec "$SOPS_BIN" -d --input-type dotenv --output-type dotenv "$ENV_FILE"
}

edit_in_place() {
  exec "$SOPS_BIN" --input-type dotenv --output-type dotenv "$ENV_FILE"
}

exec_with_env() {
  # `sops exec-env` injects the decrypted pairs straight into the child's
  # environment: values are set verbatim (a value containing `$(...)`,
  # backticks, or `$VAR` is data, never code) and no plaintext file is ever
  # created — which also removes the old non-tmpfs fallback that could land
  # a decrypted copy on the SSD. Both were review findings on PR #1256.
  if [ "$#" -eq 0 ]; then
    exec "$SOPS_BIN" exec-env "$ENV_FILE" 'env'
  elif [ "$#" -eq 1 ]; then
    # Single argument: treated as a shell command line (parity with the
    # previous `bash -c "$1"` behavior).
    exec "$SOPS_BIN" exec-env "$ENV_FILE" "$1"
  else
    # Multi-argument: re-quote so the argv survives the shell that
    # exec-env uses to launch the command, argument-for-argument.
    local quoted
    quoted=$(printf '%q ' "$@")
    exec "$SOPS_BIN" exec-env "$ENV_FILE" "$quoted"
  fi
}

case "${1:-help}" in
  decrypt|cat|show) decrypt_to_stdout ;;
  edit)             edit_in_place ;;
  help|-h|--help)   sed -n 's/^# \?//p' "$0" | head -20 ;;
  --)               shift; exec_with_env "$@" ;;
  *)                exec_with_env "$@" ;;
esac
