#!/usr/bin/env bash
# verify_existing_oauth_integrations.sh
# Verification script that checks existing OIDC integrations
# (Grafana, MinIO, Forgejo, Argo CD) are still working after updates.
#
# Usage:
#   bash k8s/talos-iam/verify_existing_oauth_integrations.sh

set -euo pipefail

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

echo "╔════════════════════════════════════════════════════════════════════╗"
echo "║  OAuth Integrations Verification                                   ║"
echo "╚════════════════════════════════════════════════════════════════════╝"
echo ""

# Check prerequisites
echo "📋 Checking prerequisites..."
required_cmds=("kubectl" "curl" "jq")
for cmd in "${required_cmds[@]}"; do
  if ! command -v "$cmd" &> /dev/null; then
    echo "❌ $cmd not found in PATH"
    exit 1
  fi
done

# Check namespaces exist
for ns in iam logging storage; do
  if ! kubectl get ns "$ns" &> /dev/null; then
    echo "❌ Namespace $ns not found"
    exit 1
  fi
done

echo "✓ All prerequisites met"
echo ""

# Function to check pod status
check_pod_status() {
  local namespace=$1
  local label=$2
  local component=$3
  
  echo "Checking $component..."
  if kubectl get pods -n "$namespace" -l "$label" -o wide 2>/dev/null | grep -q Running; then
    echo "  ✓ Running"
    return 0
  else
    echo "  ❌ Not running"
    return 1
  fi
}

# Function to test Authentik API endpoint
test_authentik_api() {
  echo "Testing Authentik API..."
  if ! kubectl port-forward -n iam svc/authentik-server 7000:80 &> /dev/null & then
    sleep 2
    if curl -sf http://localhost:7000/-/health/ready/ &> /dev/null; then
      echo "  ✓ API healthy (HTTP 204)"
    else
      echo "  ❌ API not responding"
      return 1
    fi
  fi
}

# Check core services
echo "🔍 Service Status"
echo "─────────────────────────────────────────────────────────────────────"

check_pod_status iam "app=authentik,component=server" "Authentik Server" || true
check_pod_status iam "app=authentik,component=worker" "Authentik Worker" || true
check_pod_status iam "app=authentik,component=postgresql" "Authentik PostgreSQL" || true
check_pod_status storage "app.kubernetes.io/name=vault" "Vault" || true
check_pod_status logging "app.kubernetes.io/name=grafana" "Grafana" || true
check_pod_status storage "app.kubernetes.io/name=minio" "MinIO" || true

echo ""

# Verify Authentik has expected providers
echo "🔐 Authentik OAuth Providers"
echo "─────────────────────────────────────────────────────────────────────"

if [[ -z "${AUTHENTIK_BOOTSTRAP_TOKEN:-}" ]]; then
  echo "⚠ AUTHENTIK_BOOTSTRAP_TOKEN not set — skipping provider verification"
  echo "  Set it: export AUTHENTIK_BOOTSTRAP_TOKEN=\"$(talos get cluster/AUTHENTIK_BOOTSTRAP_TOKEN --key AUTHENTIK_BOOTSTRAP_TOKEN 2>/dev/null)\""
  echo ""
else
  # Port-forward to Authentik
  if ! pgrep -f "kubectl port-forward.*7000:80" > /dev/null; then
    kubectl port-forward -n iam svc/authentik-server 7000:80 > /dev/null 2>&1 &
    sleep 2
  fi
  
  api_url="http://localhost:7000/api/v3"
  
  # Check for expected providers
  for provider in grafana minio forgejo argocd talos-cli-shell; do
    response=$(curl -sf -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \
      "${api_url}/providers/oauth2/?name=${provider}" 2>/dev/null || echo "{}")
    
    if echo "$response" | jq -e '.results[0]' &> /dev/null; then
      pk=$(echo "$response" | jq -r '.results[0].pk')
      client_id=$(echo "$response" | jq -r '.results[0].client_id // "N/A"')
      echo "  ✓ ${provider}  (pk=${pk}, client_id=${client_id})"
    else
      echo "  ✗ ${provider}  NOT FOUND"
    fi
  done
  
  echo ""
  
  # Check for expected groups
  echo "👥 Authentik Groups"
  echo "─────────────────────────────────────────────────────────────────────"
  
  for group in homelab-admins grafana-admins grafana-viewers minio-admins minio-readonly; do
    response=$(curl -sf -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \
      "${api_url}/core/groups/?name=${group}" 2>/dev/null || echo "{}")
    
    if echo "$response" | jq -e '.results[0]' &> /dev/null; then
      echo "  ✓ ${group}"
    else
      echo "  ✗ ${group}  NOT FOUND"
    fi
  done
  
  echo ""
fi

# Verify K8s secrets for apps
echo "🔑 Kubernetes Secrets"
echo "─────────────────────────────────────────────────────────────────────"

for secret_spec in "grafana-oidc:logging" "minio-oidc:storage" "authentik-oidc-forgejo:cicd" "oidc-secret:cicd"; do
  IFS=':' read -r secret_name ns <<< "$secret_spec"
  if kubectl get secret "$secret_name" -n "$ns" &> /dev/null 2>&1; then
    size=$(kubectl get secret "$secret_name" -n "$ns" -o jsonpath='{.data}' 2>/dev/null | wc -c)
    echo "  ✓ ${secret_name} → ns/${ns} (${size} bytes)"
  else
    echo "  ✗ ${secret_name} → ns/${ns}  NOT FOUND"
  fi
done

echo ""

# Verify Vault JWT auth
echo "🔐 Vault JWT Authentication"
echo "─────────────────────────────────────────────────────────────────────"

if command -v vault &> /dev/null; then
  # Check if Vault auth method is enabled
  vault_status=$(kubectl exec -n storage vault-0 -- vault auth list -format=json 2>/dev/null | jq 'keys' || echo "[]")
  
  if echo "$vault_status" | jq -e '.[] | select(. == "jwt/")' &> /dev/null; then
    echo "  ✓ JWT auth method enabled"
    
    # List JWT roles
    roles=$(kubectl exec -n storage vault-0 -- vault list auth/jwt/role -format=json 2>/dev/null | jq '.[]' || echo "")
    if [[ -n "$roles" ]]; then
      echo "  ✓ JWT roles found:"
      echo "$roles" | while read role; do
        echo "    - ${role}"
      done
    else
      echo "  ✗ No JWT roles found"
    fi
  else
    echo "  ⚠ JWT auth method not enabled"
  fi
else
  echo "  ⚠ vault CLI not found — skipping Vault checks"
fi

echo ""

# Summary
echo "╔════════════════════════════════════════════════════════════════════╗"
echo "║  Verification Complete                                             ║"
echo "╚════════════════════════════════════════════════════════════════════╝"
echo ""

echo "Next steps:"
echo ""
echo "1. Verify OIDC login flow (Grafana):"
echo "   kubectl port-forward -n logging svc/grafana 3000:80"
echo "   # Open http://localhost:3000/login"
echo "   # Should show 'Sign in with ...' option"
echo ""

echo "2. Verify MinIO OIDC (if configured):"
echo "   kubectl port-forward -n storage svc/minio 9001:9001"
echo "   # Open http://localhost:9001"
echo "   # Should show identity provider option"
echo ""

echo "3. Verify Vault JWT role:"
echo "   kubectl port-forward -n storage svc/vault 8200:8200"
echo "   export VAULT_ADDR=http://127.0.0.1:8200"
echo "   vault read auth/jwt/role/shell"
echo ""

echo "4. Test JWT authentication to Vault:"
echo "   # Get ID token from Authentik (requires app integration)"
echo "   # Then authenticate: vault login -method=jwt role=shell jwt=\$ID_TOKEN"
echo ""
