#!/usr/bin/env bash
# Update Cloudflare DNS records to point to Nginx Proxy only
# Uses .env file for Cloudflare secrets
# Never exposes backend IP addresses

set -e

# Source .env file
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
else
    echo "❌ Error: .env file not found at $PROJECT_ROOT/.env"
    exit 1
fi

# Check required variables
if [ -z "$CLOUDFLARE_ZONE_ID" ] || [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_DOMAIN" ]; then
    echo "❌ Error: Missing Cloudflare configuration in .env"
    echo "   Required: CLOUDFLARE_ZONE_ID, CLOUDFLARE_API_TOKEN, CLOUDFLARE_DOMAIN"
    exit 1
fi

# Nginx Proxy IP (should be from .env or environment)
NGINX_PROXY_IP="${NGINX_PROXY_IP:-20.160.58.99}"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔧 Updating Cloudflare DNS to Nginx Proxy Only"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📋 Configuration:"
echo "   • Zone ID: ${CLOUDFLARE_ZONE_ID:0:8}..."
echo "   • Domain: $CLOUDFLARE_DOMAIN"
echo "   • Nginx Proxy IP: $NGINX_PROXY_IP"
echo ""

# Function to get all DNS record IDs for a subdomain
get_all_record_ids() {
    local subdomain=$1
    
    curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/dns_records?name=$subdomain&type=A" \
        -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
        -H "Content-Type: application/json" | \
        python3 -c "
import sys, json
data = json.load(sys.stdin)
if data.get('success') and data.get('result'):
    for record in data['result']:
        print(record['id'])
" 2>/dev/null || echo ""
}

# Function to update DNS record
update_record() {
    local subdomain=$1
    local ip=$2
    local proxied=${3:-true}
    
    echo "   Updating $subdomain → $ip (proxied: $proxied)..."
    
    # Get all existing records
    RECORD_IDS=$(get_all_record_ids "$subdomain")
    
    if [ -z "$RECORD_IDS" ]; then
        echo "     ⚠️  No existing record found, creating new..."
        # Create new record
        RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/dns_records" \
            -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
            -H "Content-Type: application/json" \
            --data "{\"type\":\"A\",\"name\":\"$subdomain\",\"content\":\"$ip\",\"ttl\":1,\"proxied\":$proxied}")
        
        if echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); sys.exit(0 if data.get('success') else 1)" 2>/dev/null; then
            echo "     ✅ Created new record"
            return 0
        else
            echo "     ❌ Failed to create record"
            echo "$RESPONSE" | python3 -m json.tool 2>/dev/null | head -10
            return 1
        fi
    else
        # Update or delete existing records
        FIRST=true
        for RECORD_ID in $RECORD_IDS; do
            if [ "$FIRST" = true ]; then
                # Update first record to proxy IP
                RESPONSE=$(curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/dns_records/$RECORD_ID" \
                    -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
                    -H "Content-Type: application/json" \
                    --data "{\"content\":\"$ip\",\"ttl\":1,\"proxied\":$proxied}")
                
                if echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); sys.exit(0 if data.get('success') else 1)" 2>/dev/null; then
                    echo "     ✅ Updated record $RECORD_ID"
                    FIRST=false
                else
                    echo "     ❌ Failed to update record $RECORD_ID"
                    echo "$RESPONSE" | python3 -m json.tool 2>/dev/null | head -10
                    return 1
                fi
            else
                # Delete duplicate records
                RESPONSE=$(curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/dns_records/$RECORD_ID" \
                    -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
                    -H "Content-Type: application/json")
                
                if echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); sys.exit(0 if data.get('success') else 1)" 2>/dev/null; then
                    echo "     ✅ Deleted duplicate record $RECORD_ID"
                else
                    echo "     ⚠️  Failed to delete record $RECORD_ID (may not exist)"
                fi
            fi
        done
        return 0
    fi
}

# Services that should point to Nginx Proxy (proxied through Cloudflare)
declare -a PROXIED_SERVICES=(
    "explorer.d-bis.org"
    "besu.d-bis.org"
    "blockscout.d-bis.org"
    "monitoring.d-bis.org"
    "wallet.d-bis.org"
    "d-bis.org"
    "www.d-bis.org"
)

# Services that should NOT be proxied (direct IP, but still through proxy)
declare -a DIRECT_SERVICES=(
    "rpc.d-bis.org"
    "metrics.d-bis.org"
    "api.d-bis.org"
    "docs.d-bis.org"
    "grafana.d-bis.org"
    "prometheus.d-bis.org"
    "tessera.d-bis.org"
    "ws.d-bis.org"
)

echo "🔧 Updating proxied services (through Cloudflare):"
for service in "${PROXIED_SERVICES[@]}"; do
    update_record "$service" "$NGINX_PROXY_IP" "true"
done

echo ""
echo "🔧 Updating direct services (still via proxy, not proxied by CF):"
for service in "${DIRECT_SERVICES[@]}"; do
    update_record "$service" "$NGINX_PROXY_IP" "false"
done

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ DNS Update Complete"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📋 Summary:"
echo "   • All services now point to Nginx Proxy: $NGINX_PROXY_IP"
echo "   • Duplicate records removed"
echo "   • Backend IPs never exposed"
echo ""
echo "⏳ Wait 1-5 minutes for DNS propagation"
echo "🧪 Test with: dig explorer.d-bis.org"
echo ""

