#!/bin/sh
# Screen off and sleep from the kiosk power policy: computle-kioskd writes power.env and ends swayidle, which this starts again with it.
set -u
POWER=/etc/computle-kiosk/power.env
command -v swayidle >/dev/null 2>&1 || exit 0

while :; do
    SCREEN_OFF_SECONDS=900
    SLEEP_SECONDS=0
    if [ -r "$POWER" ]; then
        . "$POWER"
    fi
    set --
    if [ "$SCREEN_OFF_SECONDS" -gt 0 ] && command -v wlopm >/dev/null 2>&1; then
        set -- "$@" timeout "$SCREEN_OFF_SECONDS" "wlopm --off '*'" resume "wlopm --on '*'"
    fi
    # logind suspends after IdleActionSec of idle, which it knows only from this hint.
    if [ "$SLEEP_SECONDS" -gt 0 ]; then
        set -- "$@" idlehint 1
    fi
    if [ "$#" -eq 0 ]; then
        set -- idlehint 2147483
    fi
    swayidle -w "$@"
    status=$?
    # Exits other than being ended by computle-kioskd (the compositor gone) end the loop with the session.
    if [ "$status" -ne 143 ] && [ "$status" -ne 0 ]; then
        exit 0
    fi
done
