#!/bin/bash

# Cloudflare Tunnel Setup for Black Portal Detroit
# This bypasses CG-NAT by creating a secure tunnel to Cloudflare

set -e

echo "🔗 Setting up Cloudflare Tunnel for Black Portal Detroit..."

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   echo "This script should NOT be run as root"
   echo "Run as: ./cloudflare-tunnel-setup.sh"
   exit 1
fi

# Install cloudflared
echo "📦 Installing cloudflared..."
sudo mkdir -p --mode=0755 /usr/share/keyrings
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared bullseye main' | sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt-get update && sudo apt-get install cloudflared

# Create tunnel configuration directory
sudo mkdir -p /etc/cloudflared
sudo chown $USER:$USER /etc/cloudflared

echo ""
echo "MANUAL STEPS REQUIRED:"
echo ""
echo "1. Authenticate with Cloudflare (if not already done):"
echo "   cloudflared tunnel login"
echo ""
echo "   FOR HEADLESS PI:"
echo "   - Copy the URL that appears"
echo "   - Open it in a browser on another device"
echo "   - Complete authentication"
echo "   - If you see 'existing certificate' error, skip to step 2"
echo ""
echo "2. Create a tunnel:"
echo "   cloudflared tunnel create blackportal"
echo ""
echo "3. Copy the tunnel ID that gets displayed, then run:"
echo "   echo 'TUNNEL_ID=your-tunnel-id-here' | sudo tee /etc/cloudflared/.env"
echo ""
echo "4. Copy credentials to system location:"
echo "   sudo cp ~/.cloudflared/your-tunnel-id.json /etc/cloudflared/"
echo "   sudo chmod 600 /etc/cloudflared/your-tunnel-id.json"
echo ""
echo "5. Create DNS record in Cloudflare dashboard:"
echo "   - Type: CNAME"
echo "   - Name: @ (or blackportaldetroit.com)"
echo "   - Target: your-tunnel-id.cfargotunnel.com"
echo "   - Proxy status: Proxied (orange cloud)"
echo ""
echo "6. Run this script again to complete setup"
echo ""

# Check if tunnel already exists
if [ -f "/etc/cloudflared/.env" ]; then
    source /etc/cloudflared/.env

    if [ -z "$TUNNEL_ID" ]; then
        echo "TUNNEL_ID not found in /etc/cloudflared/.env"
        echo "Please complete manual steps above first"
        exit 1
    fi

    echo "✅ Found tunnel ID: $TUNNEL_ID"

    # Check if credentials file exists (might be in user's home or system location)
    if [ ! -f "/etc/cloudflared/$TUNNEL_ID.json" ]; then
        if [ -f "$HOME/.cloudflared/$TUNNEL_ID.json" ]; then
            echo "📋 Copying credentials from user directory..."
            sudo cp "$HOME/.cloudflared/$TUNNEL_ID.json" /etc/cloudflared/
            sudo chown root:root "/etc/cloudflared/$TUNNEL_ID.json"
            sudo chmod 600 "/etc/cloudflared/$TUNNEL_ID.json"
        else
            echo "Credentials file not found at /etc/cloudflared/$TUNNEL_ID.json"
            echo "Please run: cloudflared tunnel create blackportal"
            exit 1
        fi
    fi

    # Create tunnel configuration
    echo "📝 Creating tunnel configuration..."
    cat > /etc/cloudflared/config.yml << EOF
tunnel: $TUNNEL_ID
credentials-file: /etc/cloudflared/$TUNNEL_ID.json

ingress:
  - hostname: blackportaldetroit.com
    service: http://localhost:80
  - hostname: www.blackportaldetroit.com
    service: http://localhost:80
  - service: http_status:404
EOF

    # Set proper permissions
    sudo chown root:root /etc/cloudflared/config.yml
    sudo chmod 644 /etc/cloudflared/config.yml

    # Create systemd service
    echo "🔧 Creating systemd service..."
    sudo tee /etc/systemd/system/cloudflared.service > /dev/null << EOF
[Unit]
Description=Cloudflare Tunnel
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/cloudflared tunnel --config /etc/cloudflared/config.yml run
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

    # Enable and start service
    sudo systemctl daemon-reload
    sudo systemctl enable cloudflared
    sudo systemctl start cloudflared

    echo ""
    echo "Cloudflare Tunnel setup complete!"
    echo ""
    echo "Check status:"
    echo "sudo systemctl status cloudflared"
    echo ""
    echo "View logs:"
    echo "sudo journalctl -u cloudflared -f"
    echo ""
    echo "IMPORTANT: Did you create the DNS record?"
    echo "Go to Cloudflare Dashboard → DNS → Records"
    echo "Add CNAME: @ → $TUNNEL_ID.cfargotunnel.com"
    echo ""
    echo "Your stream should now be accessible at:"
    echo "https://blackportaldetroit.com/portal"
    echo ""
    echo "Benefits:"
    echo "  - Bypasses CG-NAT completely"
    echo "  - Free SSL certificate"
    echo "  - DDoS protection"
    echo "  - Works from anywhere"
    echo ""
    echo "Troubleshooting:"
    echo "  - If tunnel fails: Check logs with 'sudo journalctl -u cloudflared -f'"
    echo "  - If DNS doesn't work: Ensure CNAME record is added in Cloudflare"
    echo "  - If stream not accessible: Check 'sudo systemctl status nginx' and 'sudo systemctl status icecast2'"
    echo ""

else
    echo "⏳ Complete the manual steps above, then run this script again"
fi