#!/usr/bin/env bash
# Setup Cloudflare Tunnel for RPC endpoints on VMID 102
# Usage: ./setup-cloudflare-tunnel-rpc.sh <TUNNEL_TOKEN>
# Example: ./setup-cloudflare-tunnel-rpc.sh eyJhIjoiNT...

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
CLOUDFLARED_VMID="${CLOUDFLARED_VMID:-102}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if token provided
if [[ $# -eq 0 ]]; then
    error "Tunnel token required!"
    echo ""
    echo "Usage: $0 <TUNNEL_TOKEN>"
    echo ""
    echo "Get your token from Cloudflare Dashboard:"
    echo "  Zero Trust → Networks → Tunnels → Create tunnel → Copy token"
    echo ""
    exit 1
fi

TUNNEL_TOKEN="$1"

info "Setting up Cloudflare Tunnel for RPC endpoints..."
info "Proxmox Host: $PROXMOX_HOST"
info "Cloudflared Container: VMID $CLOUDFLARED_VMID"
echo ""

# Check if container is running
STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct status $CLOUDFLARED_VMID 2>/dev/null | awk '{print \$2}'" 2>/dev/null || echo "unknown")

if [[ "$STATUS" != "running" ]]; then
    error "Container $CLOUDFLARED_VMID is not running (status: $STATUS)"
    exit 1
fi

# Check if cloudflared is installed
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $CLOUDFLARED_VMID -- which cloudflared >/dev/null 2>&1"; then
    info "Installing cloudflared..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $CLOUDFLARED_VMID -- bash -c '
            mkdir -p --mode=0755 /usr/share/keyrings
            curl -fsSL https://pkg.cloudflare.com/cloudflare-public-v2.gpg | tee /usr/share/keyrings/cloudflare-public-v2.gpg >/dev/null
            echo \"deb [signed-by=/usr/share/keyrings/cloudflare-public-v2.gpg] https://pkg.cloudflare.com/cloudflared any main\" | tee /etc/apt/sources.list.d/cloudflared.list
            apt-get update -qq && apt-get install -y -qq cloudflared
        '" || {
        error "Failed to install cloudflared"
        exit 1
    }
    info "✓ cloudflared installed"
else
    info "✓ cloudflared already installed"
fi

# Stop existing cloudflared service if running
info "Stopping existing cloudflared service..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $CLOUDFLARED_VMID -- systemctl stop cloudflared 2>/dev/null || true"
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $CLOUDFLARED_VMID -- systemctl disable cloudflared 2>/dev/null || true"

# Install tunnel service with token
info "Installing tunnel service with token..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $CLOUDFLARED_VMID -- cloudflared service install $TUNNEL_TOKEN" || {
    error "Failed to install tunnel service"
    exit 1
}
info "✓ Tunnel service installed"

# Create tunnel configuration file
info "Creating tunnel configuration for RPC endpoints..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $CLOUDFLARED_VMID -- bash" <<'EOF'
cat > /etc/cloudflared/config.yml <<'CONFIG'
# Cloudflare Tunnel Configuration for RPC Endpoints
# This file is auto-generated. Manual edits may be overwritten.

ingress:
  # Public HTTP RPC
  - hostname: rpc-http-pub.d-bis.org
    service: https://192.168.11.252:443
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s

  # Public WebSocket RPC
  - hostname: rpc-ws-pub.d-bis.org
    service: https://192.168.11.252:443
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      httpHostHeader: rpc-ws-pub.d-bis.org

  # Private HTTP RPC
  - hostname: rpc-http-prv.d-bis.org
    service: https://192.168.11.252:443
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s

  # Private WebSocket RPC
  - hostname: rpc-ws-prv.d-bis.org
    service: https://192.168.11.252:443
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      httpHostHeader: rpc-ws-prv.d-bis.org

  # Catch-all (must be last)
  - service: http_status:404
CONFIG

chmod 600 /etc/cloudflared/config.yml
EOF

if [[ $? -eq 0 ]]; then
    info "✓ Tunnel configuration created"
else
    error "Failed to create tunnel configuration"
    exit 1
fi

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

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

# Wait a moment for service to start
sleep 2

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

if [[ "$STATUS" == "active" ]]; then
    info "✓ Tunnel service is running"
else
    error "Tunnel service is not active"
    warn "Checking logs..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $CLOUDFLARED_VMID -- journalctl -u cloudflared -n 20 --no-pager"
    exit 1
fi

# Show tunnel info
info "Tunnel information:"
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $CLOUDFLARED_VMID -- cloudflared tunnel info 2>/dev/null | head -10" || {
    warn "Could not retrieve tunnel info (may need a moment to connect)"
}

echo ""
info "Cloudflare Tunnel setup complete!"
echo ""
info "Next steps:"
echo "  1. Configure DNS records in Cloudflare:"
echo "     - rpc-http-pub.d-bis.org → CNAME → <tunnel-id>.cfargotunnel.com (🟠 Proxied)"
echo "     - rpc-ws-pub.d-bis.org → CNAME → <tunnel-id>.cfargotunnel.com (🟠 Proxied)"
echo "     - rpc-http-prv.d-bis.org → CNAME → <tunnel-id>.cfargotunnel.com (🟠 Proxied)"
echo "     - rpc-ws-prv.d-bis.org → CNAME → <tunnel-id>.cfargotunnel.com (🟠 Proxied)"
echo ""
echo "  2. Verify tunnel status in Cloudflare Dashboard:"
echo "     Zero Trust → Networks → Tunnels → Your Tunnel"
echo ""
echo "  3. Test endpoints:"
echo "     curl https://rpc-http-pub.d-bis.org/health"
echo ""
info "To view tunnel logs:"
echo "  ssh root@$PROXMOX_HOST 'pct exec $CLOUDFLARED_VMID -- journalctl -u cloudflared -f'"

