#!/bin/sh
# Points the kiosk Firefox window at the admin canvas URL. Installed to
# /usr/local/bin/admin-browser. Called by thinclient-agent (admin_canvas.py) when a
# "Show admin canvas" command arrives (docs/project-plan.md Phase 13).
#
# A near-copy of /usr/local/bin/digest-browser: same navigate-by-restart approach
# (Firefox's --kiosk window has no tab/address bar, and the page is stateless anyway),
# same reasoning for a --kiosk (not --new-window) launch. The one thing that matters is
# its own profile, separate from digest-browser's and web-browser's — a Firefox profile
# can only be open in one process, so sharing one would mean opening this window closed
# the digest canvas, and the pkill/pgrep patterns below are scoped to THIS profile only,
# so relaunching this window can never kill (or race against) digest-browser's — see the
# comment above digest-browser's own pkill line for the other half of that guarantee.
set -eu

PROFILE_DIR="${HOME:-/home/$(id -un)}/.mozilla/firefox/admin"

URL="${1:-${ADMIN_WEB_URL:-}}"
[ -n "$URL" ] || { echo "admin-browser: no URL given and ADMIN_WEB_URL is unset" >&2; exit 1; }

if command -v firefox-esr >/dev/null 2>&1; then
  FIREFOX=firefox-esr
else
  FIREFOX=firefox
fi

mkdir -p "$PROFILE_DIR/chrome"
cp /etc/thinclient-firefox/userChrome.css "$PROFILE_DIR/chrome/userChrome.css" 2>/dev/null || true
cp /etc/thinclient-firefox/user.js        "$PROFILE_DIR/user.js"               2>/dev/null || true

pkill -u "$(id -u)" -f "$FIREFOX .*--profile $PROFILE_DIR" 2>/dev/null || true

# Wait for the old process to release its profile lock before relaunching.
i=0
while pgrep -u "$(id -u)" -f "$FIREFOX .*--profile $PROFILE_DIR" >/dev/null 2>&1 && [ "$i" -lt 20 ]; do
  sleep 0.25
  i=$((i + 1))
done

exec "$FIREFOX" --profile "$PROFILE_DIR" --new-instance --kiosk "$URL"
