#!/bin/sh
# Chromium kiosk window pointed at identity's dashboard.html — weather + what-to-
# wear, who's home, groceries running low. Installed to /usr/local/bin/home-kiosk.
# Called both at session start and by door-panel-agent on a "Show home" MQTT command.
#
# Same kill-and-relaunch shape as hosts/kitchen-display's pantry-kiosk. Kills ANY
# chromium instance before launching (not just its own profile) — this device has
# only one workspace, same reasoning as hosts/kitchen-display's pantry-kiosk/
# identity-kiosk pair (see that host's README for the full explanation).
set -eu

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

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

encode() { printf '%s' "$1" | sed 's/\//%2F/g; s/:/%3A/g'; }

URL="${BASE_URL%/}/dashboard.html?identity_api=$(encode "$IDENTITY_URL")&identity_token=${IDENTITY_TOKEN}"
if [ -n "${PANTRY_VISION_URL:-}" ] && [ -n "${PANTRY_VISION_TOKEN:-}" ]; then
  URL="${URL}&pantry_api=$(encode "$PANTRY_VISION_URL")&pantry_token=${PANTRY_VISION_TOKEN}"
else
  echo "home-kiosk: PANTRY_VISION_URL/TOKEN unset — 'Running low' will show as unconfigured" >&2
fi

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 "home-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" \
  --start-fullscreen \
  --noerrdialogs --disable-infobars --disable-session-crashed-bubble \
  --overscroll-history-navigation=0 \
  --touch-events=enabled \
  --check-for-update-interval=31536000
