#!/bin/sh
# Opens the browsable Firefox window — minimal chrome, not kiosk mode.
# Installed to /usr/local/bin/web-browser.
#
# Separate from /usr/local/bin/digest-browser, and on a separate profile, for two
# reasons. First, the two windows want opposite chrome: the digest canvas runs --kiosk
# with no controls at all, this one keeps back/forward/reload/address bar via
# userChrome.css. Second, one Firefox profile can only be open in one process, so
# sharing a profile would mean opening the browser closed the digest, and vice versa.
#
# Both profiles get the same user.js, userChrome.css and enterprise policies (uBlock
# Origin, SponsorBlock), so extensions and prefs behave identically in each.
set -eu

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

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

mkdir -p "$PROFILE_DIR/chrome"

# Re-copied on every launch rather than once at build time: this is a locked-down kiosk
# profile with no interactive customisation expected, so keeping it in lockstep with
# /etc/thinclient-firefox/ (edited by rebuilding the image) is simpler than a one-shot
# seed that could drift after a userChrome.css update.
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

# Focus an already-open window rather than stacking a second one: unlike the digest
# canvas, this window holds state (history, a half-typed URL, a logged-in page) that a
# kill-and-relaunch would throw away.
if pgrep -u "$(id -u)" -f "$FIREFOX .*--profile $PROFILE_DIR" >/dev/null 2>&1; then
  [ -n "${1:-}" ] && exec "$FIREFOX" --profile "$PROFILE_DIR" --new-tab "$1"
  exit 0
fi

exec "$FIREFOX" --profile "$PROFILE_DIR" --new-instance --new-window "${1:-about:blank}"
