#!/bin/bash
# kiosk-session — main process of kiosk.service.
#
# Launches the weston compositor in the FOREGROUND (so it owns the logind seat
# session systemd set up via PAMName=login) and, once weston's Wayland socket is
# up, runs Chromium fullscreen in the BACKGROUND with a crash-restart loop.
#
# Why a wrapper instead of weston.ini [autolaunch]: EPEL 9 ships weston 8.0,
# which has neither kiosk-shell.so nor [autolaunch] (both weston 9.0). So weston
# runs desktop-shell.so (see weston.ini) and we start Chromium here.
#
# Process model: systemd -> this script -> exec weston. The Chromium loop is
# forked before the exec, so it lives in the unit's cgroup; when weston exits the
# service is torn down (KillMode=control-group) and the loop dies with it. If
# Chromium alone crashes, the loop relaunches it without taking weston down.
#
# KIOSK_URL comes from /etc/kiosk/kiosk.env. The Chromium profile/cache live on
# tmpfs (root is read-only erofs + volatile overlay) — writes land in RAM; watch
# RAM if the page is heavy (it can starve the NVMe-oF keep-alive — see TODO).
set -uo pipefail

: "${KIOSK_URL:?KIOSK_URL not set in /etc/kiosk/kiosk.env}"
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
SOCK=wayland-kiosk

BROWSER=$(command -v chromium-browser || command -v chromium || true)
: "${BROWSER:?chromium not found (expected chromium-browser or chromium in PATH)}"

# GPU vs software path. This image is FLEET-GENERIC: it boots both real hardware
# (e.g. the 820 / Intel HD620 -> i915) AND the virtio build/test VMs (no real
# GPU). Probe for a real KMS render node and branch — real GPU gets hardware
# raster/compositing (CPU drops off software raster); VMs keep the software path
# so weston + Chromium still render there. Pure runtime probe; no per-host state
# is baked (invariant #1).
GPU=0
case "$(basename "$(readlink -f /sys/class/drm/card0/device/driver 2>/dev/null)" 2>/dev/null)" in
    i915|amdgpu|radeon|nouveau|xe) [ -e /dev/dri/renderD128 ] && GPU=1 ;;
esac

# Lockdown flags (what the managed policy can't cover). The distro chromium
# wrapper PREPENDS its own defaults ahead of these — including its own
# --disable-features. Chromium does NOT union duplicate --disable-features (the
# LAST occurrence wins), and ours is last, so we MERGE the wrapper's disables
# (LensOverlay/Gemini/Compose/TabOrganization) into ours — otherwise they are
# silently dropped. We deliberately pass NO --enable-features, so the wrapper's
# VA-API enables (AcceleratedVideoDecodeLinuxGL, ...) stay in effect.
# Phone-home suppression (background networking, component/auto update, domain
# reliability, crash upload, pings, search-engine probe) + the comprehensive
# lockdown live in the managed policy (/etc/chromium/policies/managed/).
COMMON_FLAGS=(
    --kiosk --noerrdialogs --disable-infobars --incognito --no-first-run
    --disable-session-crashed-bubble --start-maximized
    --ozone-platform=wayland
    --disable-background-networking --disable-component-update
    --disable-sync --disable-domain-reliability --disable-breakpad
    --no-pings --no-default-browser-check --metrics-recording-only
    --disable-search-engine-collection
    "--disable-features=LensOverlay,OptimizationGuideOnDeviceModel,PromptAPIForGeminiNano,Compose,TabOrganization,Translate,OptimizationHints,OptimizationTargetPrediction,MediaRouter,AutofillServerCommunication,InterestFeedContentSuggestions"
    --user-data-dir=/tmp/kiosk-profile --disk-cache-dir=/tmp/kiosk-cache
)

if [ "$GPU" = 1 ]; then
    # Real GPU: hardware raster/compositing. HD620 (gen7 Intel) is sometimes
    # raster-blocklisted by Chromium, so override the blocklist. The GPU process
    # opens /dev/dri/renderD128 -> the kiosk user must be in group 'render' (set
    # at build, diskless.pkr.hcl). With --disable-gpu gone, the wrapper's VA-API
    # --enable-features finally engage (they need a live GPU process).
    GPU_FLAGS=(--ignore-gpu-blocklist --enable-gpu-rasterization --enable-zero-copy)
else
    GPU_FLAGS=(--disable-gpu)
fi

# Background: wait (up to ~60s) for weston's socket, then keep Chromium running.
(
    for _ in $(seq 1 120); do
        [ -S "$XDG_RUNTIME_DIR/$SOCK" ] && break
        sleep 0.5
    done
    export WAYLAND_DISPLAY="$SOCK"
    while :; do
        "$BROWSER" "${COMMON_FLAGS[@]}" "${GPU_FLAGS[@]}" "$KIOSK_URL" || true
        sleep 2
    done
) &

# weston as the foreground process (owns the seat; service restarts if it dies).
# desktop-shell + explicit socket. On real GPU use weston's GL renderer (enables
# the zero-copy dmabuf handoff from Chromium so its frames aren't CPU-copied); on
# VMs force --use-pixman (software) — there's no usable DRM/GL device there.
if [ "$GPU" = 1 ]; then
    exec weston --socket="$SOCK" --config=/etc/xdg/weston/weston.ini
else
    exec weston --use-pixman --socket="$SOCK" --config=/etc/xdg/weston/weston.ini
fi
