#!/usr/bin/env bash
# Shell helper to export secrets from a single dotenv file.
# Usage: source scripts/load-secrets.sh

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SECRETS_FILE="${SECRETS_FILE:-$ROOT_DIR/creds/secrets.env}"
ENCRYPTED_FILE="${ENCRYPTED_FILE:-$ROOT_DIR/creds/secrets.enc.env}"
KUBECONFIG_FILE="${KUBECONFIG_FILE:-$ROOT_DIR/creds/kubeconfig.yaml}"
KUBECONFIG_ENC_FILE="${KUBECONFIG_ENC_FILE:-$ROOT_DIR/creds/kubeconfig.enc.yaml}"

ensure_decrypted() {
  if [[ -f "$SECRETS_FILE" ]]; then
    return 0
  fi
  if [[ -f "$ENCRYPTED_FILE" ]]; then
    if command -v sops >/dev/null 2>&1; then
      echo "Decrypting $ENCRYPTED_FILE -> $SECRETS_FILE"
      sops -d "$ENCRYPTED_FILE" >"$SECRETS_FILE"
    else
      echo "sops not found and $SECRETS_FILE is missing. Install sops or set SECRETS_FILE." >&2
      return 1
    fi
  fi
}

ensure_decrypted || exit 0
echo "Loading secrets from $SECRETS_FILE"

set -a
source "$SECRETS_FILE"
set +a

ensure_kubeconfig() {
  # If user already set KUBECONFIG, respect it.
  if [[ -n "${KUBECONFIG:-}" ]]; then
    return 0
  fi

  if [[ -f "$KUBECONFIG_FILE" ]]; then
    export KUBECONFIG="$KUBECONFIG_FILE"
    return 0
  fi

  if [[ -f "$KUBECONFIG_ENC_FILE" ]]; then
    if command -v sops >/dev/null 2>&1; then
      echo "Decrypting $KUBECONFIG_ENC_FILE -> $KUBECONFIG_FILE"
      sops -d "$KUBECONFIG_ENC_FILE" >"$KUBECONFIG_FILE"
      export KUBECONFIG="$KUBECONFIG_FILE"
    else
      echo "sops not found and kubeconfig is missing. Install sops or set KUBECONFIG manually." >&2
      return 1
    fi
  fi
}

ensure_kubeconfig || true
