#!/bin/sh
# The general web browser — minimal chrome, not kiosk mode. Installed to
# /usr/local/bin/web-browser.
#
# The requirement this satisfies is "a web browser with uBlock Origin", which is
# enforced by /etc/firefox/policies/policies.json (force_installed, so it cannot be
# removed by a stray click on the TV) rather than by anything here.
#
# Unlike the thin client there is only one profile on this image: no digest canvas
# means no second Firefox process to keep apart. The profile still lives under a named
# directory rather than the default, because media-session's pgrep guard matches on the
# --profile path to decide whether the browser is already up.
#
# SponsorBlock is in the policy set too. On a box whose browser exists mostly to play
# video on a television, skipping sponsor segments without a remote in hand is worth
# more here than anywhere else in the house.
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
# profile with no interactive customisation expected, so keeping it in lockstep with
# /etc/steamtv-firefox/ (edited by rebuilding the image) is simpler than a one-shot seed
# that could drift after a userChrome.css update.
cp /etc/steamtv-firefox/userChrome.css "$PROFILE_DIR/chrome/userChrome.css" 2>/dev/null || true
cp /etc/steamtv-firefox/user.js        "$PROFILE_DIR/user.js"               2>/dev/null || true

# Focus an already-open window rather than stacking a second one: this window holds
# state (history, a half-typed URL, a logged-in video site) that a kill-and-relaunch
# would throw away — and media-session calls this every time somebody leaves Big
# Picture, so "already open" is the common case, not the exception.
if pgrep -u "$(id -u)" -f "$FIREFOX .*--profile $PROFILE_DIR" >/dev/null 2>&1; then
  if [ -n "${1:-}" ]; then
    exec "$FIREFOX" --profile "$PROFILE_DIR" --new-tab "$1"
  fi
  exit 0
fi

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