#!/usr/bin/env bash
# =============================================================================
#  cloudflared quick tunnel — give the Discord bot a public HTTPS URL
#  Run this on the Pi:  bash install-cloudflared.sh
#
#  What it does:
#    1. Installs cloudflared (if not already installed)
#    2. Starts a quick tunnel to the bot on port 8090
#    3. Prints the public HTTPS URL (e.g. https://random-words.trycloudflare.com)
#
#  IMPORTANT: the free trycloudflare.com URL is RANDOM and CHANGES every time
#  the tunnel restarts. After each restart you must:
#     - update bot_url in the panel's config.ini
#     - update public_base in the bot's config.json
#     - update the redirect URI in the Discord Developer Portal
# =============================================================================

set -e

BOT_PORT="${BOT_PORT:-8090}"

echo "=============================================="
echo "  cloudflared quick tunnel for the Discord bot"
echo "=============================================="

# --- 1. Install cloudflared if missing --------------------------------------
if command -v cloudflared >/dev/null 2>&1; then
    echo "[1/3] cloudflared already installed: $(cloudflared --version)"
else
    echo "[1/3] 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 $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/cloudflared.list >/dev/null
    sudo apt update
    sudo apt install -y cloudflared
    echo "    Installed: $(cloudflared --version)"
fi

# --- 2. Make sure the bot is running -----------------------------------------
echo "[2/3] Checking the bot is up on port $BOT_PORT..."
if curl -s "http://127.0.0.1:$BOT_PORT/health" >/dev/null 2>&1; then
    echo "    Bot is up on port $BOT_PORT."
else
    echo "    WARNING: bot not responding on port $BOT_PORT yet."
    echo "    Start it first with:  bash install-and-run.sh"
    echo "    (continuing anyway — the tunnel will connect once the bot is up)"
fi

# --- 3. Start the tunnel ------------------------------------------------------
echo "[3/3] Starting cloudflared tunnel to port $BOT_PORT..."
echo "    (this runs in the foreground — leave it running)"
echo ""
echo "    Your bot's public HTTPS URL will appear below as:"
echo "    https://random-words.trycloudflare.com"
echo ""
echo "    Copy that URL, then update:"
echo "      - panel config.ini  -> bot_url"
echo "      - bot config.json   -> public_base"
echo "      - Discord portal    -> redirect URI  (https://.../callback)"
echo ""
echo "    Press Ctrl+C to stop the tunnel."
echo "=============================================="

cloudflared tunnel --url "http://localhost:$BOT_PORT"
