#!/bin/sh
# Points the kiosk Firefox window at a URL. Installed to /usr/local/bin/digest-browser.
# Called both from the sway config at session start and from thinclient-agent when a
# "show digest" command arrives.
#
# Navigating by restart rather than by remote-command: Firefox's --kiosk window has no
# tab bar or address bar, and a remote `firefox <url>` against a running kiosk instance
# either opens an invisible tab or a second window that accumulates over time. Killing
# and relaunching is blunt but deterministic, and the page is stateless anyway.
#
# Its own profile, separate from /usr/local/bin/web-browser's (and, since Phase 13,
# /usr/local/bin/admin-browser's): a Firefox profile can only be open in one process,
# so sharing one would mean opening the browsable window closed the digest canvas.
# Both profiles carry the same user.js, chrome/userChrome.css and enterprise policies.
set -eu

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

URL="${1:-${DIGEST_WEB_URL:-}}"
[ -n "$URL" ] || { echo "digest-browser: no URL given and DIGEST_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

# Scoped to THIS script's own profile, not just "--kiosk" — admin-browser also runs
# --kiosk on its own separate profile (Phase 13), and a bare "--kiosk" pattern would
# kill/relaunch-race against it instead of only ever touching this script's own old
# instance.
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"
