#!/bin/sh
# Chromium kiosk window pointed at identity's registration page. Installed to
# /usr/local/bin/identity-kiosk. Called by kitchen-display-agent when a "Show
# registration" MQTT command arrives — the fallback/manual path; the primary path is
# voice ("register me as <name>"), which never touches this script at all. See
# ../../../identity/README.md.
#
# Same kill-and-relaunch shape as pantry-kiosk, on its own separate Chromium profile
# (a distinct --user-data-dir) so the two scripts' profile locks can never collide —
# but unlike hosts/thin-client's digest-browser/admin-browser (which coexist on
# separate Sway *workspaces*), this device has only ONE workspace, so this script
# also kills ANY chromium instance regardless of profile before launching, not just
# its own — otherwise switching "Show registration" -> "Show scan" would leave the
# old registration window sitting behind the new one instead of actually replacing it.
set -eu

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

BASE_URL="${IDENTITY_WEB_URL:-}"
[ -n "$BASE_URL" ] || { echo "identity-kiosk: IDENTITY_WEB_URL is unset" >&2; exit 1; }
[ -n "${IDENTITY_URL:-}" ] || { echo "identity-kiosk: IDENTITY_URL is unset" >&2; exit 1; }
[ -n "${IDENTITY_TOKEN:-}" ] || { echo "identity-kiosk: IDENTITY_TOKEN is unset" >&2; exit 1; }

DEVICE_ID="$(hostname)"
API_ENCODED="$(printf '%s' "$IDENTITY_URL" | sed 's/\//%2F/g; s/:/%3A/g')"
URL="${BASE_URL%/}/register.html?api=${API_ENCODED}&token=${IDENTITY_TOKEN}&device=${DEVICE_ID}"

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 "identity-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: same reasoning as pantry-kiosk's identical flag —
# auto-accept the camera permission prompt rather than leave it unanswered.
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
