#!/usr/bin/env bash
# Print the current Cloudflare quick-tunnel URL, or a clear status line
# if the launchd job isn't running.
#
# Usage:
#   ./scripts/tunnel-url.sh           # print URL or status
#   ./scripts/tunnel-url.sh --copy    # print URL and copy to clipboard
#
# Paired with the launchd plist at:
#   ~/Library/LaunchAgents/solutions.letsbe.pn-crm-tunnel.plist
#
# Quick ops:
#   launchctl load   ~/Library/LaunchAgents/solutions.letsbe.pn-crm-tunnel.plist  # start
#   launchctl unload ~/Library/LaunchAgents/solutions.letsbe.pn-crm-tunnel.plist  # stop
#   launchctl kickstart -k gui/$(id -u)/solutions.letsbe.pn-crm-tunnel             # restart (NEW URL)

set -euo pipefail

LOG_FILE="$HOME/Library/Logs/pn-crm-tunnel.err.log"
LABEL="solutions.letsbe.pn-crm-tunnel"

if ! launchctl print "gui/$(id -u)/$LABEL" >/dev/null 2>&1; then
    echo "Tunnel is not loaded. Start with:"
    echo "  launchctl load ~/Library/LaunchAgents/$LABEL.plist"
    exit 1
fi

if [[ ! -f "$LOG_FILE" ]]; then
    echo "Tunnel job is loaded but hasn't produced a log yet. Try again in a few seconds."
    exit 1
fi

# cloudflared prints the public URL once on startup, like:
#   https://<words>.trycloudflare.com
# Take the most recent occurrence so a restart-then-rerun picks the
# current one rather than a stale earlier line.
URL=$(grep -Eo 'https://[a-z0-9-]+\.trycloudflare\.com' "$LOG_FILE" | tail -1 || true)

if [[ -z "$URL" ]]; then
    echo "Tunnel is running but no URL has appeared in the log yet."
    echo "Tail it:  tail -f $LOG_FILE"
    exit 1
fi

echo "$URL"
echo "$URL/api/webhooks/documenso  ← paste this into Documenso webhook settings"

if [[ "${1:-}" == "--copy" ]]; then
    printf "%s/api/webhooks/documenso" "$URL" | pbcopy
    echo "(webhook URL copied to clipboard)"
fi

# Auto-PATCH Documenso's webhook URL when the env flag is set. Gated so
# production ports can never have their webhook rotated by a stale dev
# script. The TS script reads DOCUMENSO_API_URL + DOCUMENSO_API_KEY +
# DOCUMENSO_API_VERSION from .env and updates every webhook whose URL
# already points at our path OR at any *.trycloudflare.com host.
if [[ "${DEV_AUTO_UPDATE_DOCUMENSO_WEBHOOK:-}" == "1" ]]; then
    echo ""
    echo "DEV_AUTO_UPDATE_DOCUMENSO_WEBHOOK=1 — updating Documenso webhook(s)…"
    cd "$(dirname "$0")/.." || exit 1
    DEV_AUTO_UPDATE_DOCUMENSO_WEBHOOK=1 \
        pnpm tsx scripts/update-documenso-webhook.ts "$URL"
fi
