#!/usr/bin/env bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
TERRAFORM_DIR="$PROJECT_ROOT/terraform/well-architected/cloud-sovereignty"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     DEPLOYING KEY VAULTS ONLY (PHASE 1 - INFRASTRUCTURE)         ║"
echo "╚════════════════════════════════════════════════════════════════╝"

cd "$TERRAFORM_DIR"

# Check if terraform.tfvars.36regions exists
if [ ! -f "terraform.tfvars.36regions" ]; then
    echo "❌ Error: terraform.tfvars.36regions not found"
    exit 1
fi

# Create temporary tfvars with deploy_aks_clusters = false
cat terraform.tfvars.36regions | sed 's/deploy_aks_clusters = true/deploy_aks_clusters = false/' > terraform.tfvars.keyvaults

echo "Using configuration: terraform.tfvars.keyvaults"
echo "  • deploy_aks_clusters = false (Key Vaults only)"

# Initialize Terraform if needed
if [ ! -d ".terraform" ]; then
    echo "Initializing Terraform..."
    terraform init
fi

# Plan deployment
echo "=" | awk '{printf "%-64s\n", ""}'
echo "📋 RUNNING TERRAFORM PLAN"
echo "=" | awk '{printf "%-64s\n", ""}'

terraform plan -var-file=terraform.tfvars.keyvaults -out=tfplan.keyvaults

echo "=" | awk '{printf "%-64s\n", ""}'
echo "🚀 APPLYING TERRAFORM PLAN"
echo "=" | awk '{printf "%-64s\n", ""}'

echo "This will create Key Vaults across 36 regions..."
echo "Press Ctrl+C to cancel, or wait 5 seconds to continue..."
sleep 5

terraform apply tfplan.keyvaults

echo "=" | awk '{printf "%-64s\n", ""}'
echo "✅ KEY VAULT DEPLOYMENT COMPLETE"
echo "=" | awk '{printf "%-64s\n", ""}'

# Cleanup
rm -f terraform.tfvars.keyvaults

echo "Next step: Store node secrets in Key Vaults"
echo "  Run: bash scripts/key-management/store-nodes-in-keyvault.sh"

