#!/usr/bin/env bash
# Update Cloudflare Tunnel Configuration via API
# Updates tunnel ingress rules to route HTTP endpoints to central Nginx

set -euo pipefail

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Configuration
TUNNEL_ID="10ab22da-8ea3-4e2e-a896-27ece2211a05"
CENTRAL_NGINX="http://192.168.11.26:80"

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  UPDATING CLOUDFLARE TUNNEL CONFIGURATION"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Check for .env file
if [ ! -f "$ENV_FILE" ]; then
    log_error ".env file not found"
    exit 1
fi

source "$ENV_FILE"

# Determine authentication
AUTH_HEADERS=()
if [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
    AUTH_HEADERS=(-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN")
elif [ -n "${CLOUDFLARE_API_KEY:-}" ] && [ -n "${CLOUDFLARE_EMAIL:-}" ]; then
    AUTH_HEADERS=(-H "X-Auth-Email: $CLOUDFLARE_EMAIL" -H "X-Auth-Key: $CLOUDFLARE_API_KEY")
else
    log_error "No Cloudflare credentials found"
    exit 1
fi

# Get Account ID
if [ -z "${CLOUDFLARE_ACCOUNT_ID:-}" ]; then
    log_info "Getting Account ID..."
    ACCOUNT_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/accounts" \
        "${AUTH_HEADERS[@]}" \
        -H "Content-Type: application/json")
    CLOUDFLARE_ACCOUNT_ID=$(echo "$ACCOUNT_RESPONSE" | jq -r '.result[0].id // empty')
    
    if [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ "$CLOUDFLARE_ACCOUNT_ID" = "null" ]; then
        log_error "Failed to get Account ID"
        exit 1
    fi
fi

log_success "Account ID: $CLOUDFLARE_ACCOUNT_ID"
log_success "Tunnel ID: $TUNNEL_ID"

# Build ingress configuration
log_info "Building tunnel ingress configuration..."

INGRESS_CONFIG=$(jq -n \
    --arg nginx "$CENTRAL_NGINX" \
    '{
        config: {
            ingress: [
                {
                    hostname: "explorer.d-bis.org",
                    service: $nginx
                },
                {
                    hostname: "rpc-http-pub.d-bis.org",
                    service: $nginx
                },
                {
                    hostname: "rpc-http-prv.d-bis.org",
                    service: $nginx
                },
                {
                    hostname: "dbis-admin.d-bis.org",
                    service: $nginx
                },
                {
                    hostname: "dbis-api.d-bis.org",
                    service: $nginx
                },
                {
                    hostname: "dbis-api-2.d-bis.org",
                    service: $nginx
                },
                {
                    hostname: "mim4u.org",
                    service: $nginx
                },
                {
                    hostname: "www.mim4u.org",
                    service: $nginx
                },
                {
                    hostname: "rpc-ws-pub.d-bis.org",
                    service: "https://192.168.11.252:443",
                    originRequest: {
                        noTLSVerify: true,
                        httpHostHeader: "rpc-ws-pub.d-bis.org"
                    }
                },
                {
                    hostname: "rpc-ws-prv.d-bis.org",
                    service: "https://192.168.11.251:443",
                    originRequest: {
                        noTLSVerify: true,
                        httpHostHeader: "rpc-ws-prv.d-bis.org"
                    }
                },
                {
                    service: "http_status:404"
                }
            ],
            "warp-routing": {
                enabled: false
            }
        }
    }')

log_info "Updating tunnel configuration..."

# Update tunnel configuration
RESPONSE=$(curl -s -X PUT \
    "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/cfd_tunnel/${TUNNEL_ID}/configurations" \
    "${AUTH_HEADERS[@]}" \
    -H "Content-Type: application/json" \
    -d "$INGRESS_CONFIG")

if echo "$RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
    log_success "Tunnel configuration updated successfully!"
    echo ""
    log_info "Configuration will be applied within 1-2 minutes"
    log_info "Tunnel status should change from DOWN to HEALTHY"
else
    log_error "Failed to update tunnel configuration"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
    exit 1
fi

echo ""
log_info "Updated ingress rules:"
log_info "  HTTP endpoints → $CENTRAL_NGINX"
log_info "  WebSocket endpoints → Direct to RPC nodes"
echo ""

# Verify configuration
log_info "Verifying tunnel configuration..."
sleep 2
VERIFY_RESPONSE=$(curl -s -X GET \
    "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/cfd_tunnel/${TUNNEL_ID}/configurations" \
    "${AUTH_HEADERS[@]}" \
    -H "Content-Type: application/json")

if echo "$VERIFY_RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
    INGRESS_COUNT=$(echo "$VERIFY_RESPONSE" | jq '.result.config.ingress | length')
    log_success "Configuration verified: $INGRESS_COUNT ingress rules configured"
    
    echo ""
    log_info "Configured hostnames:"
    echo "$VERIFY_RESPONSE" | jq -r '.result.config.ingress[] | select(.hostname != null) | "  - \(.hostname) → \(.service)"'
else
    log_warn "Could not verify configuration (this is normal if tunnel is still updating)"
fi

echo ""
log_info "Next steps:"
log_info "  1. Wait 1-2 minutes for tunnel to reload"
log_info "  2. Check tunnel status in Cloudflare dashboard"
log_info "  3. Test endpoints:"
log_info "     curl https://explorer.d-bis.org/api/v2/stats"
log_info "     curl -X POST https://rpc-http-pub.d-bis.org \\"
log_info "       -H 'Content-Type: application/json' \\"
log_info "       -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_chainId\",\"params\":[],\"id\":1}'"
echo ""

