#!/usr/bin/env bash
# Keep a Cloudflare quick tunnel up to the local board server and record its URL.
# Cron runs this every minute; it is a no-op while the tunnel is alive.
B=/home/nadil/Dev/fpl-tools/scratch/board
LOG=$B/tunnel.log
if pgrep -x cloudflared >/dev/null; then exit 0; fi
: > "$LOG"
nohup /home/nadil/.local/bin/cloudflared tunnel --url http://localhost:8765 --no-autoupdate >> "$LOG" 2>&1 &
for i in $(seq 1 30); do
  sleep 1
  URL=$(grep -o 'https://[a-z0-9-]*\.trycloudflare\.com' "$LOG" | head -1)
  if [ -n "$URL" ]; then
    TOK=$(cat "$B/tunnel-token.txt")
    echo "$URL/b-$TOK.html" > "$B/tunnel-url.txt"
    date -u +'%Y-%m-%dT%H:%M:%SZ' > "$B/tunnel-started.txt"
    exit 0
  fi
done
echo "no URL after 30s" >> "$LOG"; exit 1
