#!/bin/sh
# Chromium kiosk window pointed at pantry-vision's frontend (pantry-web). Installed
# to /usr/local/bin/pantry-kiosk. Called both at session start and by
# kitchen-display-agent when a "Show scan/inventory/recipes" MQTT command arrives.
#
# Kill-and-relaunch, not focus-and-navigate — same reasoning as hosts/thin-client's
# digest-browser: Chromium's --kiosk window has no address bar to drive remotely, and
# the page underneath (pantry-vision/frontend/) is cheap to reload. Camera capture is
# momentary (hold item up, tap Capture) so losing an in-progress scan to a "Show
# inventory" command is an acceptable, rare edge case, not a design flaw to solve here.
#
# Kills ANY chromium instance before launching, not just this script's own profile —
# unlike hosts/thin-client's digest-browser/admin-browser (separate Sway workspaces,
# can coexist), this device has only ONE workspace, so identity-kiosk's window (a
# different profile) has to actually be replaced, not left running behind this one.
set -eu

PROFILE_DIR="${HOME:-/home/$(id -un)}/.config/kitchen-display-chromium"

BASE_URL="${PANTRY_WEB_URL:-}"
[ -n "$BASE_URL" ] || { echo "pantry-kiosk: PANTRY_WEB_URL is unset" >&2; exit 1; }
[ -n "${PANTRY_VISION_URL:-}" ] || { echo "pantry-kiosk: PANTRY_VISION_URL is unset" >&2; exit 1; }
[ -n "${PANTRY_VISION_TOKEN:-}" ] || { echo "pantry-kiosk: PANTRY_VISION_TOKEN is unset" >&2; exit 1; }

# api=/token= are read by frontend/app.js — see that file's top comment for why
# config travels this way instead of being baked into the served static files.
FRAGMENT="${1:-}"
URL="${BASE_URL%/}/index.html?api=$(printf '%s' "$PANTRY_VISION_URL" | sed 's/\//%2F/g; s/:/%3A/g')&token=${PANTRY_VISION_TOKEN}"
[ -n "$FRAGMENT" ] && URL="${URL}#${FRAGMENT}"

if command -v chromium >/dev/null 2>&1; then
  CHROMIUM=chromium
elif command -v chromium-browser >/dev/null 2>&1; then
  CHROMIUM=chromium-browser
else
  echo "pantry-kiosk: no chromium/chromium-browser binary found" >&2
  exit 1
fi

mkdir -p "$PROFILE_DIR"

pkill -u "$(id -u)" -f "$CHROMIUM --user-data-dir=" 2>/dev/null || true
i=0
while pgrep -u "$(id -u)" -f "$CHROMIUM --user-data-dir=" >/dev/null 2>&1 && [ "$i" -lt 20 ]; do
  sleep 0.25
  i=$((i + 1))
done

# --use-fake-ui-for-media-stream auto-accepts the getUserMedia camera prompt instead
# of leaving it sitting unanswered on a screen nobody is there to click "Allow" on —
# VERIFY: the simplest documented way to do this: the alternative,
# VideoCaptureAllowedUrls enterprise policy, needs a policies.json this image doesn't
# currently ship, so start with the flag and only add that if it proves insufficient.
exec "$CHROMIUM" \
  --user-data-dir="$PROFILE_DIR" \
  --ozone-platform=wayland \
  --kiosk --app="$URL" \
  --use-fake-ui-for-media-stream \
  --start-fullscreen \
  --noerrdialogs --disable-infobars --disable-session-crashed-bubble \
  --overscroll-history-navigation=0 \
  --touch-events=enabled \
  --check-for-update-interval=31536000
