#!/bin/bash
# Setup Cloudflare Tunnel

set -e

echo "Setting up Cloudflare Tunnel..."

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

# Authenticate (interactive)
echo "Please authenticate with Cloudflare..."
cloudflared tunnel login

# Create tunnel
echo "Creating tunnel..."
TUNNEL_NAME="explorer-tunnel"
cloudflared tunnel create $TUNNEL_NAME || echo "Tunnel may already exist"

# Get tunnel ID
TUNNEL_ID=$(cloudflared tunnel list | grep $TUNNEL_NAME | awk '{print $1}')

if [ -z "$TUNNEL_ID" ]; then
    echo "ERROR: Could not find tunnel ID"
    exit 1
fi

echo "Tunnel ID: $TUNNEL_ID"

# Create config directory
mkdir -p /etc/cloudflared

# Create config file
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DEPLOYMENT_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"

cat > /etc/cloudflared/config.yml << EOF
tunnel: $TUNNEL_ID
credentials-file: /etc/cloudflared/$TUNNEL_ID.json

ingress:
  - hostname: explorer.d-bis.org
    service: http://localhost:80
  - hostname: www.explorer.d-bis.org
    service: http://localhost:80
  - service: http_status:404
EOF

# Validate config
cloudflared tunnel --config /etc/cloudflared/config.yml ingress validate

# Install as service
cloudflared service install

echo "Cloudflare Tunnel configured!"
echo "Tunnel ID: $TUNNEL_ID"
echo "Config: /etc/cloudflared/config.yml"
echo ""
echo "Next steps:"
echo "1. Configure DNS routes in Cloudflare dashboard"
echo "2. Start service: systemctl start cloudflared"
echo "3. Enable on boot: systemctl enable cloudflared"

