#!/bin/bash
# kiosk-session: start a fullscreen kiosk session on the Glances dashboard.
# Installed to /usr/local/bin by install.sh — do not move.

CONFIG="$HOME/.config/headless-kiosk/config"
[[ -f "$CONFIG" ]] && source "$CONFIG"

GLANCES_URL="${GLANCES_URL:-http://127.0.0.1:61208}"
WINDOW_SIZE="${WINDOW_SIZE:-1366,768}"
CHROMIUM_BIN="${CHROMIUM_BIN:-$(command -v chromium chromium-browser 2>/dev/null | head -1)}"

if [[ -z "$CHROMIUM_BIN" ]]; then
    echo "No chromium binary found." >&2
    exit 1
fi

# Kill gnome-keyring-daemon — SDDM autologin doesn't unlock it via PAM,
# causing a password prompt. The kiosk doesn't need it (Chromium uses --password-store=basic).
pkill -f gnome-keyring-daemon 2>/dev/null || true

# Clear Chromium kiosk profile to avoid stale state and keychain prompts
rm -rf /tmp/chromium-kiosk

# Disable screensaver and DPMS
xset s off
xset -dpms
xset s noblank

# Hide the cursor when idle
unclutter -idle 1 -root &

# Auto-mount USB drives
udiskie --no-notify --no-tray &

# Wait for Glances to be available (max 30s)
for i in $(seq 1 30); do
    curl -s -o /dev/null "$GLANCES_URL" && break
    sleep 1
done

# Launch Chromium in kiosk mode with an isolated throwaway profile
# (prevents keyring prompts and interference with the user's browser state)
exec "$CHROMIUM_BIN" \
    --kiosk \
    --noerrdialogs \
    --disable-infobars \
    --no-first-run \
    --disable-session-crashed-bubble \
    --disable-restore-session-state \
    --disable-features=TranslateUI \
    --check-for-update-interval=31536000 \
    --window-size="$WINDOW_SIZE" \
    --window-position=0,0 \
    --user-data-dir=/tmp/chromium-kiosk \
    --password-store=basic \
    "$GLANCES_URL"
