#!/bin/bash
# Fix Cloudflare Configuration for Explorer Public URL
# This script configures Cloudflare DNS and tunnel for explorer.d-bis.org

set -e

EXPLORER_IP="192.168.11.140"
EXPLORER_DOMAIN="explorer.d-bis.org"
VMID=5000
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
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"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  CLOUDFLARE EXPLORER URL CONFIGURATION"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Function to execute command in container
exec_container() {
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct exec $VMID -- bash -c '$1'" 2>&1
}

# Step 1: Check Cloudflared service in container
log_info "Step 1: Checking Cloudflared service in container..."
CLOUDFLARED_STATUS=$(exec_container "systemctl is-active cloudflared 2>/dev/null || echo 'inactive'")
if [ "$CLOUDFLARED_STATUS" = "active" ]; then
    log_success "Cloudflared service is running"
else
    log_warn "Cloudflared service is $CLOUDFLARED_STATUS"
fi

# Step 2: Check Cloudflared config
log_info "Step 2: Checking Cloudflared configuration..."
CONFIG_EXISTS=$(exec_container "test -f /etc/cloudflared/config.yml && echo 'exists' || echo 'missing'")
if [ "$CONFIG_EXISTS" = "exists" ]; then
    log_success "Cloudflared config file exists"
    log_info "Current configuration:"
    exec_container "cat /etc/cloudflared/config.yml" | head -30
    echo ""
    
    # Check if explorer route exists
    EXPLORER_ROUTE=$(exec_container "grep -i explorer /etc/cloudflared/config.yml || echo 'not_found'")
    if echo "$EXPLORER_ROUTE" | grep -q "explorer"; then
        log_success "Explorer route found in config"
        echo "$EXPLORER_ROUTE"
    else
        log_warn "Explorer route not found in config"
    fi
else
    log_warn "Cloudflared config file not found"
fi

# Step 3: Get tunnel ID
log_info "Step 3: Getting tunnel ID..."
TUNNEL_ID=$(exec_container "cat /etc/cloudflared/config.yml 2>/dev/null | grep -i tunnel | head -1 | awk '{print \$2}' || echo ''")
if [ -n "$TUNNEL_ID" ]; then
    log_success "Tunnel ID: $TUNNEL_ID"
else
    log_warn "Tunnel ID not found in config"
    TUNNEL_ID=$(exec_container "cloudflared tunnel list 2>/dev/null | grep -v 'NAME' | head -1 | awk '{print \$1}' || echo ''")
    if [ -n "$TUNNEL_ID" ]; then
        log_info "Found tunnel ID from tunnel list: $TUNNEL_ID"
    else
        log_error "Cannot determine tunnel ID"
        log_info "You may need to create a tunnel or check Cloudflare dashboard"
    fi
fi

# Step 4: Check DNS record
log_info "Step 4: Checking DNS configuration..."
log_info "DNS Record should be:"
echo "  Type: CNAME"
echo "  Name: explorer"
echo "  Domain: d-bis.org"
if [ -n "$TUNNEL_ID" ]; then
    echo "  Target: $TUNNEL_ID.cfargotunnel.com"
else
    echo "  Target: <tunnel-id>.cfargotunnel.com"
fi
echo "  Proxy: 🟠 Proxied (orange cloud) - REQUIRED"
echo "  TTL: Auto"
echo ""

# Step 5: Create/update Cloudflared config
log_info "Step 5: Updating Cloudflared configuration..."
if [ "$CONFIG_EXISTS" = "exists" ]; then
    log_info "Backing up existing config..."
    exec_container "cp /etc/cloudflared/config.yml /etc/cloudflared/config.yml.backup.$(date +%Y%m%d_%H%M%S)" || true
fi

# Create updated config with explorer route
log_info "Creating updated Cloudflared configuration..."
UPDATED_CONFIG=$(cat <<EOF
tunnel: ${TUNNEL_ID:-YOUR_TUNNEL_ID}
credentials-file: /etc/cloudflared/credentials.json

ingress:
  # Explorer route
  - hostname: ${EXPLORER_DOMAIN}
    service: http://127.0.0.1:80
  
  # Catch-all (must be last)
  - service: http_status:404
EOF
)

log_info "New configuration:"
echo "$UPDATED_CONFIG"
echo ""

# Ask if we should update (or auto-update if tunnel ID found)
if [ -n "$TUNNEL_ID" ] && [ "$TUNNEL_ID" != "YOUR_TUNNEL_ID" ]; then
    log_info "Updating Cloudflared configuration..."
    echo "$UPDATED_CONFIG" | exec_container "cat > /etc/cloudflared/config.yml"
    log_success "Configuration updated"
    
    # Restart Cloudflared
    log_info "Restarting Cloudflared service..."
    exec_container "systemctl restart cloudflared" || exec_container "systemctl start cloudflared" || true
    sleep 5
    
    CLOUDFLARED_STATUS=$(exec_container "systemctl is-active cloudflared 2>/dev/null || echo 'inactive'")
    if [ "$CLOUDFLARED_STATUS" = "active" ]; then
        log_success "Cloudflared service restarted"
    else
        log_warn "Cloudflared service may not be running"
    fi
else
    log_warn "Cannot auto-update config - tunnel ID not found"
    log_info "Manual steps required:"
    echo "  1. Get tunnel ID from Cloudflare dashboard or: cloudflared tunnel list"
    echo "  2. Update /etc/cloudflared/config.yml with explorer route"
    echo "  3. Restart cloudflared: systemctl restart cloudflared"
fi

# Step 6: DNS Configuration Instructions
log_info "Step 6: DNS Configuration Required"
echo ""
log_info "You need to configure DNS in Cloudflare Dashboard:"
echo ""
echo "1. Go to: https://dash.cloudflare.com"
echo "2. Select domain: d-bis.org"
echo "3. Go to: DNS → Records"
echo "4. Add or update CNAME record:"
echo ""
echo "   Type: CNAME"
echo "   Name: explorer"
echo "   Target: ${TUNNEL_ID:-<tunnel-id>}.cfargotunnel.com"
echo "   Proxy status: 🟠 Proxied (orange cloud) - REQUIRED"
echo "   TTL: Auto"
echo ""
echo "5. Save the record"
echo ""

# Step 7: Verify configuration
log_info "Step 7: Verifying configuration..."
sleep 5

# Test local
log_info "Testing local access..."
LOCAL_TEST=$(curl -s -o /dev/null -w "%{http_code}" "http://$EXPLORER_IP/api/v2/stats" 2>&1)
if [ "$LOCAL_TEST" = "200" ]; then
    log_success "Local access: HTTP 200"
else
    log_warn "Local access: HTTP $LOCAL_TEST"
fi

# Test public URL
log_info "Testing public URL..."
PUBLIC_TEST=$(curl -s -o /dev/null -w "%{http_code}" "https://$EXPLORER_DOMAIN/api/v2/stats" 2>&1)
if [ "$PUBLIC_TEST" = "200" ]; then
    log_success "Public URL: HTTP 200 - Working!"
elif [ "$PUBLIC_TEST" = "404" ]; then
    log_warn "Public URL: HTTP 404 - DNS may not be configured yet"
    log_info "Wait 1-5 minutes for DNS propagation after configuring in Cloudflare"
elif [ "$PUBLIC_TEST" = "502" ]; then
    log_warn "Public URL: HTTP 502 - Tunnel routing issue"
else
    log_warn "Public URL: HTTP $PUBLIC_TEST"
fi

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  CONFIGURATION SUMMARY"
log_info "═══════════════════════════════════════════════════════════"
echo ""

echo "✅ Cloudflared config updated (if tunnel ID found)"
echo "⚠️  DNS configuration required in Cloudflare Dashboard"
echo ""
log_info "Next Steps:"
echo "  1. Configure DNS record in Cloudflare (see Step 6 above)"
echo "  2. Wait 1-5 minutes for DNS propagation"
echo "  3. Test: curl https://$EXPLORER_DOMAIN/api/v2/stats"
echo "  4. If still 404, check tunnel route in Cloudflare Zero Trust dashboard"
echo ""

