#!/usr/bin/env bash
# k8s/talos-iam/setup_talos_iam.sh
# Validates required env vars are set, then delegates to helmfile.
# All provisioning logic lives in helmfile hooks + provision_oidc.py.
#
# Usage:
#   vsource .env && bash k8s/talos-iam/setup_talos_iam.sh
#
# To re-provision OIDC without redeploying Authentik:
#   vsource .env && helmfile apply -l name=authentik
#
# To patch existing providers (update redirect URIs, scopes):
#   vsource .env && helmfile apply -l name=authentik  # postsync runs provision_oidc.py --patch implicitly
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
KUBECONFIG="${KUBECONFIG:-${SCRIPT_DIR}/../cluster-config/kubeconfig}"
export KUBECONFIG

# ── Validate all required secrets are loaded from Vault ──────────────────────
MISSING=()
for var in \
  AUTHENTIK_SECRET_KEY \
  AUTHENTIK_BOOTSTRAP_PASSWORD \
  AUTHENTIK_BOOTSTRAP_TOKEN \
  AUTHENTIK_PG_PASSWORD \
  GRAFANA_OIDC_CLIENT_SECRET \
  MINIO_OIDC_CLIENT_SECRET \
  AUTHENTIK_FORGEJO_CLIENT_SECRET \
  AUTHENTIK_ARGOCD_CLIENT_SECRET; do
  [[ -z "${!var:-}" ]] && MISSING+=("$var")
done

if [[ ${#MISSING[@]} -gt 0 ]]; then
  echo "ERROR: the following vars are not set — run 'vsource .env' first:" >&2
  printf '  %s\n' "${MISSING[@]}" >&2
  echo "" >&2
  echo "If a var is missing from Vault, store it first:" >&2
  echo "  talos put cluster/VAR_NAME VAR_NAME=\"\$(openssl rand -hex 32)\"" >&2
  exit 1
fi

echo "All required secrets present."
echo ""
echo "Provider credential mapping (client_id → client_secret):"
printf '  %-10s  client_id=%-40s  secret=%s\n' \
  "grafana"  "${GRAFANA_OIDC_CLIENT_ID:-"grafana (default)"}"  "GRAFANA_OIDC_CLIENT_SECRET" \
  "minio"    "${MINIO_OIDC_CLIENT_ID:-"minio (default)"}"      "MINIO_OIDC_CLIENT_SECRET" \
  "forgejo"  "${AUTHENTIK_FORGEJO_CLIENT_ID:-"forgejo (default)"}" "AUTHENTIK_FORGEJO_CLIENT_SECRET" \
  "argocd"   "${AUTHENTIK_ARGOCD_CLIENT_ID:-"argocd (default)"}"   "AUTHENTIK_ARGOCD_CLIENT_SECRET"
echo ""
echo "Delegating to helmfile..."
cd "${SCRIPT_DIR}/../.."
helmfile apply -l name=authentik
