#!/bin/sh
# Rikkiti idle daemon — runs swayidle with timeouts read from
# ~/.config/rikkiti/power.conf. Re-run it to apply changes (it replaces the
# previous instance). A timeout of 0 disables that action (e.g. desktops with no
# suspend). The `lock` handler makes `loginctl lock-session` (and the panel's Lock
# button) lock the screen.
conf="$HOME/.config/rikkiti/power.conf"
val() { grep -E "^[[:space:]]*$1[[:space:]]*=" "$conf" 2>/dev/null | tail -1 | sed 's/^[^=]*=//; s/#.*//; s/[[:space:]]//g'; }

lock_t=$(val lock_timeout);    [ -z "$lock_t" ] && lock_t=0    # default: no idle auto-lock
susp_t=$(val suspend_timeout); [ -z "$susp_t" ] && susp_t=0    # default: no idle auto-suspend
dpms_t=$(val dpms_timeout);    [ -z "$dpms_t" ] && dpms_t=0   # screen off after N s (0 = never)
before=$(val lock_before_sleep)

# Live ISO: NEVER lock or auto-suspend — a live user has no password, so any lock
# (idle, lock-before-sleep, or a loginctl lock-session from the panel) would strand
# them. live-boot mounts /run/live; the installed system is unaffected.
live=
if [ -d /run/live ]; then lock_t=0; susp_t=0; before=false; live=1; fi

pkill -x swayidle 2>/dev/null

set --
[ "$dpms_t" -gt 0 ] 2>/dev/null && set -- "$@" timeout "$dpms_t" "rikkiti-msg dpms off" resume "rikkiti-msg dpms on"
[ "$lock_t" -gt 0 ] 2>/dev/null && set -- "$@" timeout "$lock_t" rikkiti-lock
[ "$susp_t" -gt 0 ] 2>/dev/null && set -- "$@" timeout "$susp_t" "systemctl suspend"
[ "$before" != false ] && set -- "$@" before-sleep rikkiti-lock
[ -z "$live" ] && set -- "$@" lock rikkiti-lock   # loginctl lock-session / panel Lock (NOT on live)

[ "$#" -eq 0 ] && exit 0   # nothing to arm (e.g. live with DPMS off) — don't run an empty swayidle
exec swayidle -w "$@"
