#!/bin/bash
# Cloudflare Tunnel Setup for Backend VMs
# Run this script on each backend VM to expose RPC endpoints via Cloudflare Tunnel
# Automatically loads Cloudflare credentials from .env file

set -euo pipefail

# Load .env file if it exists (for Cloudflare credentials)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Navigate to project root: scripts -> phase1 -> terraform -> project root
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.env"

if [ -f "$ENV_FILE" ]; then
    echo "Loading Cloudflare credentials from .env file..."
    export $(grep -v '^#' "$ENV_FILE" | grep -E "CLOUDFLARE_" | xargs)
fi

VM_NAME="${1:-}"
DOMAIN_PREFIX="${2:-}"
CLOUDFLARE_ACCOUNT_ID="${CLOUDFLARE_ACCOUNT_ID:-${3:-}}"

if [ -z "$VM_NAME" ] || [ -z "$DOMAIN_PREFIX" ]; then
    echo "Usage: $0 <vm-name> <domain-prefix> [cloudflare-account-id]"
    echo "Example: $0 az-p-eus-vm-besu-node-0 rpc-eastus"
    echo ""
    echo "Cloudflare credentials will be loaded from .env file if available:"
    echo "  - CLOUDFLARE_ACCOUNT_ID (required)"
    echo "  - CLOUDFLARE_API_TOKEN (optional, for API-based setup)"
    exit 1
fi

if [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then
    echo "Error: CLOUDFLARE_ACCOUNT_ID is required. Set it in .env file or pass as argument."
    exit 1
fi

echo "=========================================="
echo "Cloudflare Tunnel Setup for Backend VM"
echo "=========================================="
echo "VM Name: $VM_NAME"
echo "Domain Prefix: $DOMAIN_PREFIX"
echo "Cloudflare Account ID: $CLOUDFLARE_ACCOUNT_ID"
echo ""

# Check if cloudflared is installed
if ! command -v cloudflared &> /dev/null; then
    echo "Installing cloudflared..."
    curl -L --output cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
    sudo dpkg -i cloudflared.deb || sudo apt-get install -f -y
    rm cloudflared.deb
fi

echo "Step 1: Authenticate with Cloudflare"
echo "-------------------------------------"
if [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
    echo "Cloudflare API token found in .env file."
    echo "Note: cloudflared tunnel login requires browser authentication."
    echo "The API token will be used for DNS record creation later."
    echo ""
    echo "You will be prompted to authenticate with Cloudflare via browser."
    read -p "Press Enter to continue with cloudflared tunnel login..."
    sudo cloudflared tunnel login
else
    echo "No API token found. You will be prompted to authenticate with Cloudflare."
    read -p "Press Enter to continue with cloudflared tunnel login..."
    sudo cloudflared tunnel login
fi

echo ""
echo "Step 2: Create Tunnel"
echo "---------------------"
TUNNEL_NAME="phase1-backend-${VM_NAME}"
echo "Creating tunnel: $TUNNEL_NAME"
TUNNEL_OUTPUT=$(sudo cloudflared tunnel create "$TUNNEL_NAME" 2>&1)
TUNNEL_ID=$(echo "$TUNNEL_OUTPUT" | grep -oP '(?<=Created tunnel )[a-f0-9-]+' || echo "")

if [ -z "$TUNNEL_ID" ]; then
    echo "Error: Could not extract tunnel ID. Please check the output above."
    exit 1
fi

echo "Tunnel created with ID: $TUNNEL_ID"

echo ""
echo "Step 3: Configure Tunnel"
echo "------------------------"
DOMAIN="${DOMAIN_PREFIX}.yourdomain.com"  # Replace with your actual domain
sudo tee /etc/cloudflared/config.yml > /dev/null <<EOF
tunnel: $TUNNEL_ID
credentials-file: /root/.cloudflared/$TUNNEL_ID.json

ingress:
  # RPC HTTP endpoint
  - hostname: ${DOMAIN}
    path: /rpc
    service: http://localhost:8545
  # WebSocket endpoint
  - hostname: ${DOMAIN}
    path: /ws
    service: ws://localhost:8546
  # Metrics endpoint (optional, restrict access)
  - hostname: ${DOMAIN}
    path: /metrics
    service: http://localhost:9545
  # Catch-all rule
  - service: http_status:404
EOF

echo "Configuration written to /etc/cloudflared/config.yml"

echo ""
echo "Step 4: Create Route in Cloudflare"
echo "----------------------------------"
echo "Creating DNS route in Cloudflare..."
sudo cloudflared tunnel route dns "$TUNNEL_NAME" "$DOMAIN"

echo ""
echo "Step 5: Enable and Start Service"
echo "--------------------------------"
sudo systemctl daemon-reload
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
sudo systemctl status cloudflared --no-pager

echo ""
echo "=========================================="
echo "Cloudflare Tunnel Setup Complete!"
echo "=========================================="
echo "Tunnel ID: $TUNNEL_ID"
echo "Domain: $DOMAIN"
echo "RPC Endpoint: http://localhost:8545"
echo "WebSocket Endpoint: ws://localhost:8546"
echo ""
echo "Next steps:"
echo "1. Update Nginx proxy to use Cloudflare Tunnel endpoints instead of private IPs"
echo "2. Verify tunnel status: sudo cloudflared tunnel info $TUNNEL_ID"
echo "3. View tunnel logs: sudo journalctl -u cloudflared -f"
echo ""

