#!/usr/bin/env bash
# screen-lock (module screen-lock, novox/hq ADR 0208): the locker. xss-lock runs it on idle, before
# suspend and on logind's Lock, and node-lock-screen's `lock` ends in it.
#
# The distribution's i3lock: a black screen, failed attempts shown, an empty Enter ignored. The colour
# build the predecessor used is not in the distribution; it can come back as a pinned archive
# (ADR 0205), and then only these options change.
#
# Before a suspend, xss-lock hands this script a lock on the sleep (XSS_SLEEP_LOCK_FD) and suspends
# once it is released. The locker must not inherit it, or the machine would wait for the unlock
# before sleeping; it is released once i3lock is up, so the machine never sleeps unlocked. This is
# xss-lock's own documented pattern for i3lock.
set -u

options=(--color=000000 --show-failed-attempts --ignore-empty-password)

# One locker: a second press of the key, or a lock while locked, changes nothing.
if pgrep -xu "$EUID" i3lock >/dev/null; then
	exit 0
fi

if [[ -e /dev/fd/${XSS_SLEEP_LOCK_FD:--1} ]]; then
	kill_i3lock() { pkill -xu "$EUID" "$@" i3lock; }
	trap kill_i3lock TERM INT
	i3lock "${options[@]}" {XSS_SLEEP_LOCK_FD}<&-
	exec {XSS_SLEEP_LOCK_FD}<&-
	while kill_i3lock -0; do
		sleep 0.5
	done
else
	trap 'kill %%' TERM INT
	i3lock --nofork "${options[@]}" &
	wait
fi
