#!/bin/bash
# Install and Configure Cloudflare Tunnel for Explorer
# Uses the provided tunnel token

set -e

TUNNEL_TOKEN="eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiYjAyZmUxZmUtY2I3ZC00ODRlLTkwOWItN2NjNDEyOThlYmU4IiwicyI6Ik5HTmtOV0kwWXpNdFpUVmxaUzAwTVRFMkxXRXdNMk10WlRJNU1ETTFaRFF4TURBMiJ9"

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

# 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 "  INSTALLING CLOUDFLARE TUNNEL FOR EXPLORER"
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 if cloudflared is installed
log_info "Step 1: Checking cloudflared installation..."
CLOUDFLARED_INSTALLED=$(exec_container "command -v cloudflared >/dev/null 2>&1 && echo 'yes' || echo 'no'")
if [ "$CLOUDFLARED_INSTALLED" = "no" ]; then
    log_info "Installing cloudflared..."
    exec_container "cd /tmp && wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && dpkg -i cloudflared-linux-amd64.deb || apt install -f -y" || {
        log_error "Failed to install cloudflared"
        exit 1
    }
    log_success "cloudflared installed"
else
    log_success "cloudflared already installed"
fi

# Step 2: Install service with token
log_info "Step 2: Installing cloudflared service with tunnel token..."
log_info "This will configure the tunnel automatically..."

# Install service using the token
INSTALL_OUTPUT=$(exec_container "cloudflared service install $TUNNEL_TOKEN 2>&1" || echo "FAILED")

if echo "$INSTALL_OUTPUT" | grep -q -E "successfully|installed|Service installed"; then
    log_success "Service installed successfully"
    echo "$INSTALL_OUTPUT" | head -10
else
    log_warn "Service installation output:"
    echo "$INSTALL_OUTPUT"
    # Continue anyway - service might already be installed
fi

# Step 3: Check service status
log_info "Step 3: Checking service status..."
sleep 3
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"
    log_info "Starting service..."
    exec_container "systemctl start cloudflared" || true
    exec_container "systemctl enable cloudflared" || true
    sleep 3
    CLOUDFLARED_STATUS=$(exec_container "systemctl is-active cloudflared 2>/dev/null || echo 'inactive'")
    if [ "$CLOUDFLARED_STATUS" = "active" ]; then
        log_success "Service started"
    else
        log_warn "Service may need manual start"
    fi
fi

# Step 4: Check configuration
log_info "Step 4: Checking tunnel 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 ""
    
    # 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"
    else
        log_warn "Explorer route not found - may need manual configuration"
    fi
else
    log_warn "Config file not found - service may use token-based auth"
fi

# Step 5: Get tunnel information
log_info "Step 5: Getting tunnel information..."
TUNNEL_INFO=$(exec_container "cloudflared tunnel list 2>&1" || echo "")
if [ -n "$TUNNEL_INFO" ]; then
    log_info "Tunnel list:"
    echo "$TUNNEL_INFO"
    echo ""
    
    # Try to extract tunnel ID
    TUNNEL_ID=$(echo "$TUNNEL_INFO" | grep -v "NAME" | head -1 | awk '{print $1}' || echo "")
    if [ -n "$TUNNEL_ID" ]; then
        log_success "Tunnel ID: $TUNNEL_ID"
    fi
else
    log_warn "Could not list tunnels"
fi

# Step 6: Verify service
log_info "Step 6: Verifying service..."
exec_container "systemctl status cloudflared --no-pager -l | head -15" || true

# Step 7: Test public URL
log_info "Step 7: Testing public URL..."
sleep 5
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 route may need configuration"
    log_info "Check Cloudflare dashboard for DNS and tunnel route configuration"
elif [ "$PUBLIC_HTTP" = "502" ]; then
    log_warn "Public URL: HTTP 502 - Tunnel routing issue"
else
    log_warn "Public URL: HTTP $PUBLIC_HTTP"
fi

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  INSTALLATION SUMMARY"
log_info "═══════════════════════════════════════════════════════════"
echo ""

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

if [ -n "$TUNNEL_ID" ]; then
    log_success "✓ Tunnel ID: $TUNNEL_ID"
    echo ""
    log_info "DNS Configuration Required:"
    echo "  Type: CNAME"
    echo "  Name: explorer"
    echo "  Target: $TUNNEL_ID.cfargotunnel.com"
    echo "  Proxy: 🟠 Proxied (orange cloud)"
    echo ""
else
    log_warn "✗ Tunnel ID: Not found"
    log_info "Check Cloudflare Zero Trust dashboard for tunnel ID"
fi

if [ "$PUBLIC_HTTP" = "200" ]; then
    log_success "✓ Public URL: Working!"
else
    log_warn "✗ Public URL: HTTP $PUBLIC_HTTP"
    log_info "Next steps:"
    echo "  1. Configure DNS: explorer → <tunnel-id>.cfargotunnel.com (🟠 Proxied)"
    echo "  2. Configure tunnel route: explorer.d-bis.org → http://$EXPLORER_IP:80"
    echo "  3. Wait 1-5 minutes for DNS propagation"
    echo "  4. Test: curl https://$EXPLORER_DOMAIN/api/v2/stats"
fi

echo ""

