#!/bin/bash
# Check Cloudflare Configuration for Explorer
# Shows current status and what needs to be configured

set -e

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

# 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 CONFIGURATION CHECK"
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
}

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

# Check config file
log_info "2. Checking Cloudflared Configuration..."
if exec_container "test -f /etc/cloudflared/config.yml"; then
    log_success "Config file exists"
    log_info "Current configuration:"
    exec_container "cat /etc/cloudflared/config.yml" | head -30
    echo ""
    
    # Extract tunnel ID
    TUNNEL_ID=$(exec_container "grep -i '^tunnel:' /etc/cloudflared/config.yml | awk '{print \$2}' | head -1" || echo "")
    if [ -n "$TUNNEL_ID" ]; then
        log_success "Tunnel ID: $TUNNEL_ID"
    else
        log_warn "Tunnel ID not found in config"
    fi
    
    # Check for explorer route
    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 "Config file not found: /etc/cloudflared/config.yml"
fi

# Check DNS resolution
log_info "3. Checking DNS Resolution..."
DNS_RESULT=$(dig +short "$EXPLORER_DOMAIN" 2>/dev/null | head -1 || echo "")
if [ -n "$DNS_RESULT" ]; then
    log_success "DNS resolves to: $DNS_RESULT"
    if echo "$DNS_RESULT" | grep -qE "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$"; then
        # Check if it's a Cloudflare IP
        if echo "$DNS_RESULT" | grep -qE "^(104\.|172\.64\.|172\.65\.|172\.66\.|172\.67\.)"; then
            log_success "DNS points to Cloudflare (proxied)"
        else
            log_warn "DNS points to non-Cloudflare IP (may not be proxied)"
        fi
    fi
else
    log_warn "DNS does not resolve"
fi

# Test public URL
log_info "4. Testing Public URL..."
PUBLIC_HTTP=$(curl -s -o /dev/null -w "%{http_code}" "https://$EXPLORER_DOMAIN/api/v2/stats" 2>&1)
if [ "$PUBLIC_HTTP" = "200" ]; then
    log_success "Public URL: HTTP 200 - Working!"
    PUBLIC_RESPONSE=$(curl -s "https://$EXPLORER_DOMAIN/api/v2/stats" 2>&1)
    if echo "$PUBLIC_RESPONSE" | grep -q -E "total_blocks|chain_id"; then
        log_success "Public API: Valid response"
    fi
elif [ "$PUBLIC_HTTP" = "404" ]; then
    log_warn "Public URL: HTTP 404 - DNS/tunnel not configured"
elif [ "$PUBLIC_HTTP" = "502" ]; then
    log_warn "Public URL: HTTP 502 - Tunnel routing issue"
else
    log_warn "Public URL: HTTP $PUBLIC_HTTP"
fi

# Summary
echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  CONFIGURATION SUMMARY"
log_info "═══════════════════════════════════════════════════════════"
echo ""

if [ "$CLOUDFLARED_STATUS" = "active" ]; then
    log_success "✓ Cloudflared service: Running"
else
    log_error "✗ Cloudflared service: Not running"
fi

if exec_container "test -f /etc/cloudflared/config.yml"; then
    log_success "✓ Config file: Exists"
    if [ -n "$TUNNEL_ID" ]; then
        log_success "✓ Tunnel ID: $TUNNEL_ID"
    else
        log_warn "✗ Tunnel ID: Not found"
    fi
    if echo "$EXPLORER_ROUTE" | grep -q "explorer"; then
        log_success "✓ Explorer route: Configured"
    else
        log_warn "✗ Explorer route: Not configured"
    fi
else
    log_error "✗ Config file: Not found"
fi

if [ -n "$DNS_RESULT" ]; then
    log_success "✓ DNS: Resolves"
else
    log_error "✗ DNS: Does not resolve"
fi

if [ "$PUBLIC_HTTP" = "200" ]; then
    log_success "✓ Public URL: Working"
else
    log_warn "✗ Public URL: HTTP $PUBLIC_HTTP"
fi

echo ""
if [ "$PUBLIC_HTTP" != "200" ]; then
    log_info "Configuration Required:"
    echo ""
    if [ -n "$TUNNEL_ID" ]; then
        echo "1. DNS Record (Cloudflare Dashboard):"
        echo "   Type: CNAME"
        echo "   Name: explorer"
        echo "   Target: $TUNNEL_ID.cfargotunnel.com"
        echo "   Proxy: 🟠 Proxied (orange cloud)"
        echo ""
        echo "2. Tunnel Route (Cloudflare Zero Trust):"
        echo "   Subdomain: explorer"
        echo "   Domain: d-bis.org"
        echo "   Service: http://$EXPLORER_IP:80"
        echo ""
    else
        echo "1. Find your tunnel ID:"
        echo "   - Check Cloudflare Zero Trust dashboard"
        echo "   - Or run: cloudflared tunnel list (in container)"
        echo ""
        echo "2. Configure DNS and tunnel route (see docs/CLOUDFLARE_EXPLORER_SETUP_COMPLETE.md)"
        echo ""
    fi
fi

echo ""

