#!/bin/sh
# Persistent Chromium kiosk window pointed at Home Assistant. Installed to
# /usr/local/bin/ha-kiosk. Launched once at session start (configs/sway/config) and
# supervised right here with a restart loop, not by sway (its `exec` has no
# restart-on-crash) or systemd (this needs the graphical session's env, and a system
# unit chasing a per-session Wayland socket is more trouble than a two-line loop).
#
# Unlike hosts/thin-client's digest-browser, this is never killed-and-relaunched on
# an MQTT command — touchpanel_agent.sway_control.launch_app()'s is_running/
# focus_criteria path just switches workspace and focuses the existing window, since
# the HA dashboard is stateful (login session, scroll position, which view you left
# it on) and reloading it on every "show home" tap would throw that away for nothing.
set -eu

PROFILE_DIR="${HOME:-/home/$(id -un)}/.config/touchpanel-chromium-ha"
URL="${HA_URL:-}"
[ -n "$URL" ] || { echo "ha-kiosk: HA_URL is unset" >&2; exit 1; }

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 "ha-kiosk: no chromium/chromium-browser binary found" >&2
  exit 1
fi

mkdir -p "$PROFILE_DIR"

# VERIFY: Chromium's Wayland app_id for a --app= kiosk window is assumed to start
# with "chromium" (matched by configs/sway/config's [app_id="chromium.*"] and by
# touchpanel_agent's focus_criteria) — not confirmed against a real build. If the
# fullscreen/for_window rule or the "Home" dock button's focus-instead-of-relaunch
# stops working, check the real app_id with `swaymsg -t get_tree`.
while true; do
  "$CHROMIUM" \
    --user-data-dir="$PROFILE_DIR" \
    --ozone-platform=wayland \
    --kiosk --app="$URL" \
    --start-fullscreen \
    --noerrdialogs --disable-infobars --disable-session-crashed-bubble \
    --overscroll-history-navigation=0 \
    --touch-events=enabled \
    --check-for-update-interval=31536000 \
    >/tmp/ha-kiosk.log 2>&1 || true
  sleep 2
done
