#!/bin/sh
# Rikkiti lock screen — swayidle (idle, before-sleep, loginctl lock-session) and the panel's Lock button all run THIS.
#
# It returns once the screen is hidden, the locker carrying on in the background (as swaylock -f does): swayidle's
# before-sleep then returns with the screen already hidden, and swayidle (run with -w) isn't held up for as long as
# the screen is locked, which stopped its screen-off and idle suspend. The locker (rikkiti-locker) says it has the
# lock on --ready-fd. If it doesn't within READY_WAIT seconds, or exits first (it couldn't lock), swaylock locks
# instead. When a lock already holds the session, swaylock is refused as well, and nothing changes.
#
# And should the locker die once it has locked — a crash, a kill — the session would stay locked on a black screen
# with nothing to type into: a fallback locker takes its place (the Skald one, then swaylock).
READY_WAIT="${RIKKITI_LOCK_READY_WAIT:-8}"

# swaylock, themed from the Rikkiti accent (appearance.conf).
swaylock_themed() {
	ap="$HOME/.config/rikkiti/appearance.conf"
	accent="4cbf73"; dark=1  # default = rikkiti green (ACCENTS[2])
	if [ -f "$ap" ]; then
		a=$(grep -E '^[[:space:]]*accent[[:space:]]*=' "$ap" | tail -1 | sed 's/.*=//; s/[[:space:]]//g; s/^#//')
		[ -n "$a" ] && accent="$a"
		grep -qiE '^[[:space:]]*dark[[:space:]]*=[[:space:]]*(false|0|no)' "$ap" && dark=0
	fi
	if [ "$dark" = 1 ]; then bg=1e1e2e; txt=cdd6f4; else bg=eff1f5; txt=4c4f69; fi
	swaylock \
		--color "$bg" \
		--inside-color "${bg}cc" \
		--ring-color "$accent" \
		--key-hl-color "$accent" \
		--bs-hl-color ff5555 \
		--line-color 00000000 \
		--separator-color 00000000 \
		--text-color "$txt" \
		--ring-ver-color "$accent" \
		--ring-wrong-color ff5555 \
		--indicator-radius 90 \
		--indicator-thickness 8 \
		"$@"
}

# keep_locked runs the locker and, should it end with the session maybe still locked, a fallback in its place.
# rikkiti-locker exits 0 once it has unlocked, 3 when the compositor refused the lock (another holds the session), 4
# when it never locked (the swaylock below covers that); anything else is a locker gone while locked.
keep_locked() {
	rikkiti-locker --ready-fd 3
	rc=$?
	exec 3>&-
	case "$rc" in 0|3|4) return 0 ;; esac
	echo "rikkiti-lock: rikkiti-locker ended ($rc), the session maybe still locked; a fallback locker takes over" >&2
	if command -v rikkiti-locker-skald >/dev/null 2>&1 && rikkiti-locker-skald; then return 0; fi
	swaylock_themed
}

if command -v rikkiti-locker >/dev/null 2>&1; then
	# keep_locked's fd 3 is the pipe (its output goes nowhere); `wc -c` counts the newline written once locked.
	ready=$( { keep_locked 3>&1 >/dev/null & } | timeout "$READY_WAIT" head -c 1 | wc -c )
	[ "$ready" = 1 ] && exit 0
	echo "rikkiti-lock: rikkiti-locker didn't take the lock; swaylock instead" >&2
fi
swaylock_themed -f "$@"
