#!/usr/bin/env bash
# Manual Cloudflare configuration instructions for Blockscout Explorer
# This script provides instructions and can help check existing configuration

set -euo pipefail

EXPLORER_DOMAIN="explorer.d-bis.org"
EXPLORER_IP="192.168.11.140"
EXPLORER_PORT="80"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_section() { echo -e "${CYAN}════════════════════════════════════════${NC}"; }

log_section
log_info "Cloudflare Configuration for Blockscout Explorer"
log_section
echo ""

log_info "Domain: $EXPLORER_DOMAIN"
log_info "Target: http://$EXPLORER_IP:$EXPLORER_PORT"
echo ""

# Try to get tunnel information
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

log_section
log_info "Step 1: Get Tunnel ID"
log_section

log_info "Checking tunnel configuration on VMID 102..."
TUNNEL_INFO=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct exec 102 -- cloudflared tunnel list 2>&1" | head -10 || echo "")

if [ -n "$TUNNEL_INFO" ]; then
    echo "$TUNNEL_INFO"
    TUNNEL_ID=$(echo "$TUNNEL_INFO" | grep -oP '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}' | head -1 || echo "")
    if [ -n "$TUNNEL_ID" ]; then
        log_success "Found tunnel ID: $TUNNEL_ID"
        TUNNEL_TARGET="${TUNNEL_ID}.cfargotunnel.com"
    else
        log_warn "Could not extract tunnel ID from output"
        TUNNEL_TARGET="<tunnel-id>.cfargotunnel.com"
    fi
else
    log_warn "Could not get tunnel information"
    log_info "You can find your tunnel ID in Cloudflare Zero Trust Dashboard:"
    log_info "  https://one.dash.cloudflare.com/ → Zero Trust → Networks → Tunnels"
    TUNNEL_TARGET="<tunnel-id>.cfargotunnel.com"
fi

echo ""
log_section
log_info "Step 2: Configure DNS Record"
log_section

log_info "Go to Cloudflare DNS Dashboard:"
log_info "  https://dash.cloudflare.com/ → Select domain 'd-bis.org' → DNS → Records"
echo ""
log_info "Create CNAME record:"
echo ""
echo "  Type: CNAME"
echo "  Name: explorer"
echo "  Target: $TUNNEL_TARGET"
echo "  Proxy status: 🟠 Proxied (orange cloud) - REQUIRED"
echo "  TTL: Auto"
echo ""
log_warn "IMPORTANT: Proxy must be enabled (orange cloud) for tunnel to work!"

echo ""
log_section
log_info "Step 3: Configure Tunnel Route"
log_section

log_info "Go to Cloudflare Zero Trust Dashboard:"
log_info "  https://one.dash.cloudflare.com/"
log_info "  Navigate to: Zero Trust → Networks → Tunnels"
echo ""
log_info "Select your tunnel, then click 'Configure' → 'Public Hostnames'"
log_info "Add a new hostname:"
echo ""
echo "  Subdomain: explorer"
echo "  Domain: d-bis.org"
echo "  Service: http://$EXPLORER_IP:$EXPLORER_PORT"
echo "  Type: HTTP"
echo ""
log_info "Click 'Save hostname'"

echo ""
log_section
log_info "Step 4: Verify Configuration"
log_section

log_info "After configuration, test with:"
echo ""
echo "  # Wait 1-5 minutes for DNS propagation"
echo "  dig $EXPLORER_DOMAIN"
echo "  curl https://$EXPLORER_DOMAIN/health"
echo ""

log_section
log_info "Current Status Check"
log_section

log_info "Checking if DNS record exists..."
DNS_CHECK=$(dig +short "$EXPLORER_DOMAIN" 2>&1 | head -3 || echo "")
if [ -n "$DNS_CHECK" ] && [ "$DNS_CHECK" != ";; connection timed out; no servers could be reached" ]; then
    log_success "DNS record exists: $DNS_CHECK"
else
    log_warn "DNS record not found or not yet propagated"
fi

log_info "Testing HTTPS endpoint..."
HTTP_TEST=$(curl -I -s --max-time 10 "https://$EXPLORER_DOMAIN" 2>&1 | head -5 || echo "")
if echo "$HTTP_TEST" | grep -q "HTTP/2 200\|HTTP/1.1 200"; then
    log_success "HTTPS endpoint is working!"
elif echo "$HTTP_TEST" | grep -q "HTTP/2 522"; then
    log_warn "HTTP 522 (Connection Timeout) - Tunnel may not be configured yet"
elif echo "$HTTP_TEST" | grep -q "HTTP/2 404"; then
    log_warn "HTTP 404 - DNS configured but tunnel route may be missing"
else
    log_warn "Endpoint not accessible: $HTTP_TEST"
fi

echo ""
log_success "Configuration instructions complete!"
echo ""
log_info "Summary:"
log_info "  1. DNS: CNAME explorer → $TUNNEL_TARGET (🟠 Proxied)"
log_info "  2. Tunnel: explorer.d-bis.org → http://$EXPLORER_IP:$EXPLORER_PORT"
log_info "  3. Test: curl https://$EXPLORER_DOMAIN/health"
echo ""

