#!/usr/bin/env bash
# Setup Cloudflared Tunnel for ThirdWeb RPC Node (VMID 2400)
# This script installs Cloudflared and configures it to connect to Cloudflare Tunnel
#
# Usage: ./scripts/setup-cloudflared-vmid2400.sh <TUNNEL_TOKEN>
# Example: ./scripts/setup-cloudflared-vmid2400.sh eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0Ijoi...

set -euo pipefail

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

# Configuration
VMID=2400
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
HOSTNAME="thirdweb-rpc-1"
IP="192.168.11.240"

# 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}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if token provided
if [[ $# -eq 0 ]]; then
    log_error "Tunnel token required!"
    echo ""
    echo "Usage: $0 <TUNNEL_TOKEN>"
    echo ""
    echo "Get your token from Cloudflare Dashboard:"
    echo "  1. Go to: https://one.dash.cloudflare.com/"
    echo "  2. Navigate to: Zero Trust → Networks → Tunnels"
    echo "  3. Click: Create a tunnel"
    echo "  4. Select: Cloudflared"
    echo "  5. Name: thirdweb-rpc-2400"
    echo "  6. Copy the token shown"
    echo ""
    exit 1
fi

TUNNEL_TOKEN="$1"

log_info "═══════════════════════════════════════════════════════════"
log_info "  SETTING UP CLOUDFLARE TUNNEL FOR VMID 2400"
log_info "═══════════════════════════════════════════════════════════"
echo ""
log_info "VMID: $VMID"
log_info "Hostname: $HOSTNAME"
log_info "IP: $IP"
log_info "Proxmox Host: $PROXMOX_HOST"
echo ""

# Check SSH access
log_info "Checking SSH access to $PROXMOX_HOST..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "echo 'SSH OK'" &>/dev/null; then
    log_error "Cannot access $PROXMOX_HOST via SSH"
    log_error "Please ensure:"
    log_error "  1. SSH key is set up"
    log_error "  2. Host is reachable"
    log_error "  3. Root access is available"
    exit 1
fi
log_success "SSH access confirmed"

# Check container status
log_info "Checking container status..."
CONTAINER_STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct status $VMID 2>/dev/null | awk '{print \$2}'" 2>/dev/null || echo "unknown")

if [[ "$CONTAINER_STATUS" != "running" ]]; then
    log_warn "Container $VMID is not running (status: $CONTAINER_STATUS)"
    log_info "Attempting to start container..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "pct start $VMID" || {
        log_error "Failed to start container $VMID"
        exit 1
    }
    sleep 5
    log_success "Container started"
else
    log_success "Container is running"
fi

# Install cloudflared
log_info "Checking cloudflared installation..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- command -v cloudflared >/dev/null 2>&1"; then
    log_info "Installing cloudflared..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- bash -c 'apt update -qq && apt install -y wget && 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

# Verify cloudflared version
CLOUDFLARED_VERSION=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- cloudflared --version 2>&1 | head -1" || echo "unknown")
log_info "cloudflared version: $CLOUDFLARED_VERSION"

# Install tunnel service
log_info "Installing tunnel service with token..."
INSTALL_OUTPUT=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- cloudflared service install \"$TUNNEL_TOKEN\" 2>&1" || echo "INSTALL_FAILED")

if echo "$INSTALL_OUTPUT" | grep -q -E "successfully|installed|Service installed"; then
    log_success "Tunnel service installed"
elif echo "$INSTALL_OUTPUT" | grep -q -E "already installed|exists"; then
    log_warn "Tunnel service may already be installed"
else
    log_warn "Installation output: $INSTALL_OUTPUT"
    # Continue - service might already be installed
fi

# Enable and start service
log_info "Enabling and starting cloudflared service..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl enable cloudflared" || log_warn "Failed to enable service (may already be enabled)"

ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl start cloudflared" || {
    log_error "Failed to start cloudflared service"
    exit 1
}

# Wait for service to start
sleep 5

# Check service status
log_info "Checking cloudflared service status..."
SERVICE_STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl is-active cloudflared 2>/dev/null || echo 'inactive'")

if [[ "$SERVICE_STATUS" == "active" ]]; then
    log_success "Cloudflared service is running"
else
    log_warn "Cloudflared service status: $SERVICE_STATUS"
    log_info "Checking logs for issues..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- journalctl -u cloudflared -n 20 --no-pager" || true
fi

# Get tunnel information
log_info "Getting tunnel information..."
TUNNEL_LIST=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- cloudflared tunnel list 2>&1" || echo "")

if echo "$TUNNEL_LIST" | grep -q -E "NAME|ID"; then
    echo ""
    log_info "Tunnel list:"
    echo "$TUNNEL_LIST" | head -10
    echo ""
else
    log_warn "Could not retrieve tunnel list"
fi

# Check tunnel configuration
log_info "Checking tunnel configuration..."
TUNNEL_CONFIG=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- cat /etc/cloudflared/config.yml 2>/dev/null || echo 'Config not found'")

if [[ "$TUNNEL_CONFIG" != "Config not found" ]] && [[ -n "$TUNNEL_CONFIG" ]]; then
    log_info "Tunnel config exists"
    echo "$TUNNEL_CONFIG" | head -20
    echo ""
else
    log_warn "Tunnel config file not found (this is normal for token-based installation)"
fi

# Summary
echo ""
log_success "═══════════════════════════════════════════════════════════"
log_success "  CLOUDFLARE TUNNEL SETUP COMPLETE"
log_success "═══════════════════════════════════════════════════════════"
echo ""
log_info "Next steps:"
echo ""
echo "1. Configure Tunnel Route in Cloudflare Dashboard:"
echo "   - Go to: https://one.dash.cloudflare.com/"
echo "   - Navigate to: Zero Trust → Networks → Tunnels"
echo "   - Click on your tunnel name"
echo "   - Click: Configure"
echo "   - Go to: Public Hostname tab"
echo "   - Click: Add a public hostname"
echo "   - Configure:"
echo "     Subdomain: rpc.public-0138"
echo "     Domain: defi-oracle.io"
echo "     Service Type: HTTP"
echo "     URL: http://127.0.0.1:8545"
echo "   - Click: Save hostname"
echo ""
echo "2. Configure DNS Record in Cloudflare:"
echo "   - Go to: DNS → Records"
echo "   - Select domain: defi-oracle.io"
echo "   - Click: Add record"
echo "   - Configure:"
echo "     Type: CNAME"
echo "     Name: rpc.public-0138"
echo "     Target: <your-tunnel-id>.cfargotunnel.com"
echo "     Proxy: 🟠 Proxied (orange cloud)"
echo "     TTL: Auto"
echo "   - Click: Save"
echo ""
echo "3. Verify Setup:"
echo "   - Wait 1-2 minutes for DNS propagation"
echo "   - Test: curl -k https://rpc.public-0138.defi-oracle.io \\"
echo "            -X POST -H 'Content-Type: application/json' \\"
echo "            -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'"
echo ""
log_info "For detailed instructions, see: docs/04-configuration/THIRDWEB_RPC_CLOUDFLARE_SETUP.md"
echo ""
