#!/bin/bash
# Cloudflare Tunnel Setup Script for Nginx Proxy
# Run this script on the Nginx proxy VM after SSH access is established
# 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

NGINX_PROXY_IP="${1:-}"
DOMAIN_NAME="${2:-}"

if [ -z "$DOMAIN_NAME" ]; then
    echo "Usage: $0 <domain-name> [nginx-proxy-ip]"
    echo "Example: $0 rpc.yourdomain.com 20.160.58.99"
    echo ""
    echo "Cloudflare credentials will be loaded from .env file if available:"
    echo "  - CLOUDFLARE_ZONE_ID"
    echo "  - CLOUDFLARE_ACCOUNT_ID"
    echo "  - CLOUDFLARE_API_TOKEN"
    exit 1
fi

NGINX_PROXY_IP="${NGINX_PROXY_IP:-20.160.58.99}"

echo "=========================================="
echo "Cloudflare Tunnel Setup for Nginx Proxy"
echo "=========================================="
echo "Nginx Proxy IP: $NGINX_PROXY_IP"
echo "Domain Name: $DOMAIN_NAME"
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."
    echo "Open the URL shown below and complete authentication."
    echo ""
    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."
    echo "Open the URL shown in your browser and complete authentication."
    echo ""
    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-nginx-proxy"
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 "------------------------"
sudo tee /etc/cloudflared/config.yml > /dev/null <<EOF
tunnel: $TUNNEL_ID
credentials-file: /root/.cloudflared/$TUNNEL_ID.json

ingress:
  # Route your domain to Nginx HTTPS
  - hostname: $DOMAIN_NAME
    service: https://localhost:443
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
  # 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..."

# Use API token if available
if [ -n "${CLOUDFLARE_API_TOKEN:-}" ] && [ -n "${CLOUDFLARE_ZONE_ID:-}" ]; then
    echo "Using Cloudflare API to create DNS record..."
    # Extract subdomain and domain
    DOMAIN_PART=$(echo "$DOMAIN_NAME" | cut -d'.' -f1)
    ZONE_DOMAIN=$(echo "$DOMAIN_NAME" | cut -d'.' -f2-)
    
    # Create CNAME record via API
    curl -X POST "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/dns_records" \
      -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
      -H "Content-Type: application/json" \
      --data "{\"type\":\"CNAME\",\"name\":\"${DOMAIN_NAME}\",\"content\":\"${TUNNEL_ID}.cfargotunnel.com\",\"ttl\":3600,\"proxied\":true}" \
      || echo "Warning: Failed to create DNS record via API. Creating via cloudflared CLI..."
    
    # Fallback to CLI method
    sudo cloudflared tunnel route dns "$TUNNEL_NAME" "$DOMAIN_NAME" || true
else
    sudo cloudflared tunnel route dns "$TUNNEL_NAME" "$DOMAIN_NAME"
fi

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_NAME"
echo "Nginx Proxy: https://localhost:443"
echo ""
echo "Next steps:"
echo "1. Verify DNS propagation: dig $DOMAIN_NAME"
echo "2. Check tunnel status: sudo cloudflared tunnel info $TUNNEL_ID"
echo "3. View tunnel logs: sudo journalctl -u cloudflared -f"
echo "4. Configure SSL/TLS in Cloudflare Dashboard (SSL/TLS -> Overview -> Full or Full (strict))"
echo ""

