#!/bin/bash
# Non-interactive Cloudflare Tunnel Setup
# Assumes user is already logged into Cloudflare via browser

set -euo pipefail

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

# Load domain from .env
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | grep -E "CLOUDFLARE_DOMAIN" | xargs)
    if [ -n "${CLOUDFLARE_DOMAIN:-}" ]; then
        DOMAIN_NAME="rpc.${CLOUDFLARE_DOMAIN}"
    else
        RPC_URL=$(grep "^RPC_URL=" "$ENV_FILE" 2>/dev/null | cut -d'=' -f2 | tr -d '"' || echo "")
        if [ -n "$RPC_URL" ]; then
            DOMAIN_NAME=$(echo "$RPC_URL" | sed 's|https\?://||' | sed 's|/.*||')
        fi
    fi
fi

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

if [ -z "$DOMAIN_NAME" ]; then
    echo "Error: No domain name found"
    exit 1
fi

echo "=========================================="
echo "Cloudflare Tunnel Setup"
echo "=========================================="
echo "Domain: $DOMAIN_NAME"
echo ""

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

# Check if already logged in
if sudo test -f /root/.cloudflared/cert.pem; then
    echo "✓ Already authenticated with Cloudflare"
elif sudo cloudflared tunnel list > /dev/null 2>&1; then
    echo "✓ Authentication verified (can list tunnels)"
else
    echo "⚠ Not authenticated. Run: sudo cloudflared tunnel login"
    echo "This will show a URL - open it in your browser to authenticate."
    exit 1
fi

# Create tunnel
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
    # Check if tunnel already exists
    EXISTING_TUNNEL=$(sudo cloudflared tunnel list 2>/dev/null | grep "$TUNNEL_NAME" | awk '{print $1}' || echo "")
    if [ -n "$EXISTING_TUNNEL" ]; then
        echo "Tunnel already exists: $EXISTING_TUNNEL"
        TUNNEL_ID="$EXISTING_TUNNEL"
    else
        echo "Error: Could not create or find tunnel"
        echo "$TUNNEL_OUTPUT"
        exit 1
    fi
fi

echo "Tunnel ID: $TUNNEL_ID"

# Configure tunnel
echo ""
echo "Configuring tunnel..."
sudo tee /etc/cloudflared/config.yml > /dev/null <<EOF
tunnel: $TUNNEL_ID
credentials-file: /root/.cloudflared/$TUNNEL_ID.json

ingress:
  - hostname: $DOMAIN_NAME
    service: https://localhost:443
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
  - service: http_status:404
EOF

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

# Create DNS record via API
echo ""
echo "Creating DNS record..."
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | grep -E "CLOUDFLARE_" | xargs)
    if [ -n "${CLOUDFLARE_API_TOKEN:-}" ] && [ -n "${CLOUDFLARE_ZONE_ID:-}" ]; then
        RESPONSE=$(curl -s -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}")
        
        SUCCESS=$(echo "$RESPONSE" | jq -r '.success // false' 2>/dev/null || echo "false")
        if [ "$SUCCESS" = "true" ]; then
            echo "✓ DNS record created via API"
        else
            echo "⚠ DNS record creation via API failed, using CLI..."
            sudo cloudflared tunnel route dns "$TUNNEL_NAME" "$DOMAIN_NAME" || true
        fi
    else
        sudo cloudflared tunnel route dns "$TUNNEL_NAME" "$DOMAIN_NAME"
    fi
else
    sudo cloudflared tunnel route dns "$TUNNEL_NAME" "$DOMAIN_NAME"
fi

# Enable and start service
echo ""
echo "Enabling and starting Cloudflared service..."
sudo systemctl daemon-reload
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
sleep 2
sudo systemctl status cloudflared --no-pager | head -15

echo ""
echo "=========================================="
echo "Cloudflare Tunnel Setup Complete!"
echo "=========================================="
echo "Tunnel ID: $TUNNEL_ID"
echo "Domain: $DOMAIN_NAME"
echo ""
echo "Verify:"
echo "  curl https://$DOMAIN_NAME/health"
echo ""

