#!/usr/bin/env bash
# Opens KIOSK_URL fullscreen, in a fresh profile.
# Run by talking-heads@.service (talking-heads browser) inside cage.

CONFIG=/etc/talking-heads/config
[[ -f "$CONFIG" ]] && source "$CONFIG"

KIOSK_URL="${KIOSK_URL:-http://localhost/}"

# Snap browsers (Ubuntu) are only in the login PATH
PATH="$PATH:/snap/bin"

# First installed browser matching KIOSK_BROWSER (any of them when empty)
case "${KIOSK_BROWSER:-}" in
    chromium*) candidates="chromium chromium-browser" ;;
    firefox*) candidates="firefox firefox-esr" ;;
    *) candidates="chromium chromium-browser firefox firefox-esr" ;;
esac
for name in $candidates; do
    BROWSER=$(command -v "$name") && break
done
if [[ -z "$BROWSER" ]]; then
    echo "talking-heads: no browser found (tried: $candidates)" >&2
    exit 1
fi

# Fresh profile on each start: no restore prompts, no stale state. In a
# visible folder of the kiosk user's home, the only place snap browsers
# can write to.
PROFILE="$HOME/browser-profile"
rm -rf "$PROFILE"
mkdir -p "$PROFILE"

# Wait for the page to answer (max 30s), e.g. a local server still starting
for _ in $(seq 1 30); do
    curl -s -o /dev/null --max-time 2 "$KIOSK_URL" && break
    sleep 1
done

echo "talking-heads: opening $KIOSK_URL with $BROWSER" >&2

case "$(basename "$BROWSER")" in
    firefox*)
        # Skip the first-run pages of a new profile
        cat >"$PROFILE/user.js" <<'EOF'
user_pref("browser.aboutwelcome.enabled", false);
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.sessionstore.resume_from_crash", false);
user_pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
EOF
        export MOZ_ENABLE_WAYLAND=1
        exec "$BROWSER" --kiosk --no-remote --profile "$PROFILE" "$KIOSK_URL"
        ;;
    *)
        exec "$BROWSER" \
            --kiosk \
            --ozone-platform=wayland \
            --noerrdialogs \
            --disable-infobars \
            --no-first-run \
            --disable-session-crashed-bubble \
            --disable-restore-session-state \
            --disable-features=TranslateUI \
            --check-for-update-interval=31536000 \
            --password-store=basic \
            --user-data-dir="$PROFILE" \
            "$KIOSK_URL"
        ;;
esac
