#!/bin/sh
# Togen signage kiosk launcher for Wayland desktops (DVI-1210).
#
# Used on boxes that already boot into a Wayland desktop with a display manager
# and autologin -- most notably Raspberry Pi OS (lightdm + labwc). Started from
# the autologin user's labwc autostart, it runs INSIDE the existing Wayland
# session (WAYLAND_DISPLAY + XDG_RUNTIME_DIR are already set), so -- unlike the
# headless xsession path -- it never starts its own X/Wayland server and never
# needs root or --no-sandbox. Respawns Chromium if it exits.
set -u

CONF=/etc/togen-signage/agent.conf
TOKEN_FILE=/etc/togen-signage/agent.token
PROFILE_DIR="${HOME:-/tmp}/.togen-signage-chromium"

if [ -f "$CONF" ]; then
  # shellcheck disable=SC1090
  . "$CONF"
fi
if [ -z "${TOGEN_HOST:-}" ]; then
  echo "TOGEN_HOST not set in $CONF" >&2
  exit 1
fi
if [ ! -r "$TOKEN_FILE" ]; then
  echo "cannot read agent token at $TOKEN_FILE (is this the kiosk user?)" >&2
  exit 1
fi

CHROME_BIN=$(command -v chromium 2>/dev/null || command -v chromium-browser 2>/dev/null || true)
if [ -z "$CHROME_BIN" ]; then
  echo "chromium/chromium-browser not found on PATH" >&2
  exit 1
fi

mkdir -p "$PROFILE_DIR"

# Respawn: if Chromium is closed/crashes, relaunch. Re-read the token each loop
# so a re-enroll (new token written to $TOKEN_FILE) is picked up on next launch.
while :; do
  AGENT_TOKEN=$(cat "$TOKEN_FILE")
  URL="$TOGEN_HOST/display?token=$AGENT_TOKEN"
  "$CHROME_BIN" \
    --kiosk \
    --ozone-platform=wayland \
    --noerrdialogs \
    --disable-infobars \
    --incognito \
    --no-first-run \
    --disable-translate \
    --disable-session-crashed-bubble \
    --disable-pinch \
    --overscroll-history-navigation=0 \
    --autoplay-policy=no-user-gesture-required \
    --check-for-update-interval=31536000 \
    --user-data-dir="$PROFILE_DIR" \
    "$URL" || true
  sleep 3
done
