#!/bin/sh
# Chromium kiosk window pointed at identity's registration page. Installed to
# /usr/local/bin/identity-kiosk. Called by door-panel-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.
#
# Identical script to hosts/kitchen-display/configs/sway/identity-kiosk — kept as a
# separate copy per this project's "duplicated, not shared, across hosts" convention.
set -eu

PROFILE_DIR="${HOME:-/home/$(id -un)}/.config/door-panel-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

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
