#!/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 operator's look, adopted from the predecessor's my-i3lock: the screen as it was, blurred, with
# an orange ring, the time and the date. That needs i3lock-color, from the distribution's user
# repository, kept as found until the mesh carries such software (novox/hq research 027, question 1).
# On a machine without it the distribution's i3lock shows the same blurred screen, taken here, with
# its own plain ring; failing that, black.
#
# 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

# 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

# The colour build numbers its versions <n>.c.<n> (2.13.c.5); its version line never says "color".
if i3lock --version 2>&1 | grep -qE '[0-9]\.c\.[0-9]'; then
	blank='#00000000' clear='#ffffff22' accent='#ca4a00' wrong='#880000bb' verifying='#bb00bbbb'
	options=(
		--insidever-color="$clear" --ringver-color="$verifying"
		--insidewrong-color="$clear" --ringwrong-color="$wrong"
		--inside-color="$blank" --ring-color="$accent" --line-color="$blank" --separator-color="$accent"
		--verif-color="$accent" --wrong-color="$accent" --time-color="$accent" --date-color="$accent"
		--layout-color="$accent" --keyhl-color="$wrong" --bshl-color="$wrong"
		--screen 1 --blur 5 --ring-width=7.0 --clock --indicator
		--time-str="%H:%M:%S" --date-str="%A, %Y-%m-%d"
		--time-font=sans-serif --date-font=sans-serif --verif-font=sans-serif
		--wrong-font=sans-serif --layout-font=sans-serif --keylayout 1
		--show-failed-attempts --ignore-empty-password
	)
else
	options=(--color=000000 --show-failed-attempts --ignore-empty-password)
	shot="${XDG_RUNTIME_DIR:-/tmp}/screen-lock.png"
	if command -v magick >/dev/null && magick import -window root -resize 25% -blur 0x3 -resize 400% "$shot" 2>/dev/null; then
		options+=(--image="$shot")
	fi
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
