#!/bin/bash

# Cloudflare Tunnel Setup Script for FastMCP Google Workspace MCP Server
# This script helps you create and configure a permanent Cloudflare tunnel

set -e

echo "========================================"
echo "FastMCP Cloudflare Tunnel Setup"
echo "========================================"
echo ""

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

# Check if cloudflared is installed
if ! command -v cloudflared &> /dev/null; then
    echo -e "${RED}Error: cloudflared is not installed${NC}"
    echo ""
    echo "Please install cloudflared first:"
    echo "  macOS:   brew install cloudflared"
    echo "  Linux:   Download from https://github.com/cloudflare/cloudflared/releases"
    echo "  Windows: Download from https://github.com/cloudflare/cloudflared/releases"
    exit 1
fi

echo -e "${GREEN}✓ cloudflared is installed${NC}"
echo ""

# Check if user is logged in to Cloudflare
echo "Checking Cloudflare authentication..."
if ! cloudflared tunnel list &> /dev/null; then
    echo -e "${YELLOW}You need to log in to Cloudflare first${NC}"
    echo ""
    echo "Running: cloudflared tunnel login"
    echo "This will open your browser for authentication..."
    cloudflared tunnel login
    echo ""
fi

echo -e "${GREEN}✓ Authenticated with Cloudflare${NC}"
echo ""

# Ask for tunnel name
read -p "Enter a name for your tunnel (default: fastmcp-server): " TUNNEL_NAME
TUNNEL_NAME=${TUNNEL_NAME:-fastmcp-server}

# Check if tunnel already exists
echo "Checking if tunnel '$TUNNEL_NAME' exists..."
if cloudflared tunnel list | grep -q "$TUNNEL_NAME"; then
    echo -e "${YELLOW}Tunnel '$TUNNEL_NAME' already exists${NC}"
    read -p "Do you want to use the existing tunnel? (y/n): " USE_EXISTING
    
    if [[ $USE_EXISTING != "y" ]]; then
        echo "Please choose a different tunnel name and run the script again."
        exit 1
    fi
    
    # Get tunnel ID
    TUNNEL_ID=$(cloudflared tunnel list | grep "$TUNNEL_NAME" | awk '{print $1}')
else
    # Create new tunnel
    echo "Creating new tunnel: $TUNNEL_NAME"
    TUNNEL_OUTPUT=$(cloudflared tunnel create "$TUNNEL_NAME")
    TUNNEL_ID=$(echo "$TUNNEL_OUTPUT" | grep -oP '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}' | head -1)
    
    if [ -z "$TUNNEL_ID" ]; then
        echo -e "${RED}Failed to create tunnel${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✓ Tunnel created successfully${NC}"
fi

echo ""
echo "Tunnel ID: $TUNNEL_ID"
echo ""

# Ask for hostname
read -p "Enter your desired hostname (e.g., fastmcp.yourdomain.com): " TUNNEL_HOSTNAME

if [ -z "$TUNNEL_HOSTNAME" ]; then
    echo -e "${RED}Hostname is required${NC}"
    exit 1
fi

# Create credentials directory if it doesn't exist
mkdir -p credentials

# Copy tunnel credentials to the credentials directory
CLOUDFLARED_DIR="$HOME/.cloudflared"
CRED_FILE="$CLOUDFLARED_DIR/${TUNNEL_ID}.json"

if [ -f "$CRED_FILE" ]; then
    cp "$CRED_FILE" credentials/tunnel-credentials.json
    echo -e "${GREEN}✓ Tunnel credentials copied to credentials/tunnel-credentials.json${NC}"
else
    echo -e "${RED}Warning: Could not find credentials file at $CRED_FILE${NC}"
    echo "You may need to copy it manually."
fi

# Create .env.cloudflare file
echo "Creating .env.cloudflare configuration file..."
cat > .env.cloudflare << EOF
# Cloudflare Tunnel Configuration
# Generated by setup-cloudflare-tunnel.sh

# Tunnel Identification
TUNNEL_ID=${TUNNEL_ID}
TUNNEL_NAME=${TUNNEL_NAME}
TUNNEL_HOSTNAME=${TUNNEL_HOSTNAME}

# Tunnel Settings
TUNNEL_METRICS=0.0.0.0:2000
TUNNEL_LOGLEVEL=info
EOF

echo -e "${GREEN}✓ Created .env.cloudflare${NC}"
echo ""

# Configure DNS
echo "========================================" 
echo "DNS Configuration Required"
echo "========================================"
echo ""
echo "You need to configure DNS for your tunnel:"
echo ""
echo "Run this command to set up DNS routing:"
echo -e "${YELLOW}cloudflared tunnel route dns $TUNNEL_NAME $TUNNEL_HOSTNAME${NC}"
echo ""
read -p "Would you like to run this command now? (y/n): " SETUP_DNS

if [[ $SETUP_DNS == "y" ]]; then
    echo "Setting up DNS..."
    cloudflared tunnel route dns "$TUNNEL_NAME" "$TUNNEL_HOSTNAME"
    echo -e "${GREEN}✓ DNS configured successfully${NC}"
else
    echo -e "${YELLOW}Remember to run the DNS command later:${NC}"
    echo "  cloudflared tunnel route dns $TUNNEL_NAME $TUNNEL_HOSTNAME"
fi

echo ""
echo "========================================" 
echo "Setup Complete!"
echo "========================================"
echo ""
echo "Your tunnel has been configured:"
echo "  Tunnel Name: $TUNNEL_NAME"
echo "  Tunnel ID:   $TUNNEL_ID"
echo "  Hostname:    $TUNNEL_HOSTNAME"
echo ""
echo "To start your FastMCP server with the tunnel:"
echo "  docker-compose up -d"
echo ""
echo "Your FastMCP server will be accessible at:"
echo -e "  ${GREEN}https://$TUNNEL_HOSTNAME${NC}"
echo ""
echo "To check tunnel status:"
echo "  cloudflared tunnel info $TUNNEL_NAME"
echo ""
echo "To view tunnel logs:"
echo "  docker-compose logs -f cloudflared"
echo ""