#!/bin/sh
# rikkiti-suspend — suspend, but not while something is holding sleep off.
#
# A block inhibitor on sleep (Files copying, an update installing) means "not now":
# logind would refuse, or pop up a password prompt to override it, and the copy
# would be cut off. So while one is held this waits — locking the screen first
# with --lock, as for a closed lid — and suspends as soon as nothing blocks sleep.
# The compositor ends the wait when the lid opens; swayidle's resume runs --cancel.
#
#   rikkiti-suspend [--lock]   suspend now, or once nothing blocks sleep
#   rikkiti-suspend --cancel   stop a waiting rikkiti-suspend (the user came back)
pidfile="${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/rikkiti-suspend.pid}"

held() { # a block-mode inhibitor whose WHAT includes sleep (delay-mode ones don't count)
	systemd-inhibit --list --no-pager --no-legend 2>/dev/null |
		grep -Eq '(^|[[:space:]:])sleep([[:space:]:]|$).*[[:space:]]block$'
}

if [ "${1:-}" = --cancel ]; then
	[ -n "$pidfile" ] && [ -r "$pidfile" ] || exit 0
	{ read -r pid; read -r script; } < "$pidfile"
	# only a waiting rikkiti-suspend, never whatever process has that number now
	if [ -n "$pid" ] && tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -qF -- "$script"; then
		kill "$pid" 2>/dev/null
	fi
	rm -f "$pidfile"
	exit 0
fi

held || exec systemctl suspend

[ "${1:-}" = --lock ] && rikkiti-lock >/dev/null 2>&1 &
command -v notify-send >/dev/null 2>&1 &&
	notify-send -a Rikkiti "Staying awake for now" "Something is still working, like Files copying. Rikkiti will sleep when it finishes." 2>/dev/null
[ -n "$pidfile" ] && printf '%s\n%s\n' "$$" "$0" > "$pidfile"
trap '[ -n "$pidfile" ] && rm -f "$pidfile"; exit 0' TERM INT
while held; do sleep 10; done
[ -n "$pidfile" ] && rm -f "$pidfile"
exec systemctl suspend
