#!/usr/bin/env bash
# Complete Phase 2 deployment from proxy host
# Run this script ON the Nginx proxy host (20.160.58.99)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# 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

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Phase 2 Complete Deployment from Proxy Host"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Verify SSH key
if [ -z "$SSH_PRIVATE_KEY_PATH" ]; then
    echo "ERROR: SSH_PRIVATE_KEY_PATH not available. Set it in smom-dbis-138/.env or repo .env." >&2
    exit 1
fi

if [ ! -f "$SSH_PRIVATE_KEY_PATH" ]; then
    echo "❌ Error: SSH key not found: $SSH_PRIVATE_KEY_PATH"
    exit 1
fi

# Set proper permissions
chmod 600 "$SSH_PRIVATE_KEY_PATH"
echo "✅ SSH key configured: $SSH_PRIVATE_KEY_PATH"

# Step 1: Generate Phase 2 configuration
echo ""
echo "Step 1: Generating Phase 2 configuration..."
./scripts/deployment/generate-phase2-tfvars.sh

# Step 2: Initialize Terraform
echo ""
echo "Step 2: Initializing Terraform..."
cd terraform/phases/phase2
if [ ! -d .terraform ]; then
    terraform init -upgrade > /dev/null 2>&1
fi
echo "✅ Terraform initialized"

# Step 3: Deploy Phase 2
echo ""
echo "Step 3: Deploying Phase 2 to all 5 regions (parallel)..."
terraform apply -auto-approve
echo "✅ Phase 2 deployed"

# Step 4: Start services
echo ""
echo "Step 4: Starting services on all regions (parallel)..."
cd "$PROJECT_ROOT"
./terraform/phases/phase2/scripts/start-services.sh all

# Step 5: Verify deployment
echo ""
echo "Step 5: Verifying deployment..."
./terraform/phases/phase2/scripts/status.sh all

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Phase 2 Deployment Complete!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
