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

if [[ $# -eq 0 ]]; then
  echo "usage: bin/kis-sops-env <command> [args...]" >&2
  exit 64
fi

sops_bin="${SOPS_BIN:-sops}"
if ! command -v "$sops_bin" >/dev/null 2>&1; then
  if [[ -x /opt/homebrew/bin/sops ]]; then
    sops_bin="/opt/homebrew/bin/sops"
  fi
fi

if ! command -v "$sops_bin" >/dev/null 2>&1; then
  echo "sops is required to load KIS runtime secrets" >&2
  exit 127
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
secret_file="${KIS_SOPS_FILE:-$repo_root/secrets/kis.live.sops.yaml}"

if [[ ! -f "$secret_file" ]]; then
  echo "KIS SOPS file not found: $secret_file" >&2
  exit 66
fi

"$sops_bin" -d --output-type json "$secret_file" | python3 -c '
import json
import os
import sys

cmd = sys.argv[1:]
if not cmd:
    raise SystemExit("missing command")

data = json.load(sys.stdin)
env = os.environ.copy()
for key, value in data.items():
    if value is None:
        continue
    if isinstance(value, (str, int, float, bool)):
        env[str(key)] = str(value)

os.execvpe(cmd[0], cmd, env)
' "$@"
