#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 The Dodobian authors
#
# lock: lock the screen with gtklock and return once it is locked. Run by swayidle
# (dodo-idle.service) when the session is locked and before sleep, which swayidle holds back (-w)
# until this returns, so the machine never sleeps on an unlocked screen.
#   - Locked means a gtklock of this user runs and $XDG_RUNTIME_DIR/dodo-locked exists, a marker
#     gtklock makes once the screen is locked and removes when it is unlocked. Already locked (e.g.
#     Suspend pressed on the lock screen): nothing to do. The marker outlives the lock by the few
#     milliseconds gtklock takes to close after an unlock; a sleep begun in that instant, as the
#     password is accepted, is not caught.
#   - Otherwise this waits for the marker, starting gtklock when none runs: a gtklock still locking
#     is waited for, one that exits without locking (just unlocked, or failed) is started again,
#     twice at most. gtklock outlives this script (dodo-idle.service keeps it: KillMode=process).
#     gtklock -d would wait only one second. The wait ends after 5 seconds, logind's longest sleep
#     delay, with a line in the journal.
#   - The password field goes on the primary monitor, primary= of session.conf, which the session
#     hands to systemd as XFW_PRIMARY_MONITOR (an output name or a comma-separated list of them);
#     without it, gtklock puts it on its first monitor.
set -eu
uid=$(id -u)
rt=${XDG_RUNTIME_DIR:?lock: XDG_RUNTIME_DIR is not set}
marker=$rt/dodo-locked
# running: is a gtklock of this user running? pgrep's errors are not a "no".
running() {
	rc=0
	pgrep -u "$uid" -x gtklock >/dev/null || rc=$?
	case $rc in
	0) return 0 ;;
	1) return 1 ;;
	*) echo "lock: pgrep failed ($rc): could not tell whether the screen is locked" >&2; exit 2 ;;
	esac
}
if [ -e "$marker" ]; then
	if running; then exit 0; fi
	rm -f "$marker" # left by a gtklock that died: not a lock
fi
set --
if [ -n "${XFW_PRIMARY_MONITOR:-}" ]; then
	old_ifs=$IFS
	IFS=,
	# shellcheck disable=SC2086 # split the comma-separated list of output names on purpose
	for m in $XFW_PRIMARY_MONITOR; do set -- "$@" --monitor-priority "$m"; done
	IFS=$old_ifs
fi
i=0
starts=0
started_at=-10
while [ ! -e "$marker" ]; do
	# A second after a start, so that a gtklock still on its way is not taken for a dead one.
	if [ $((i - started_at)) -ge 10 ] && ! running; then
		[ "$starts" -lt 2 ] || { echo "lock: gtklock exited twice without locking the screen" >&2; exit 1; }
		# Its messages go where ours go: the journal of dodo-idle.service.
		setsid gtklock "$@" -L "touch $marker" -U "rm -f $marker" </dev/null &
		starts=$((starts + 1))
		started_at=$i
	fi
	[ "$i" -lt 50 ] || { echo "lock: the screen did not lock within 5 seconds" >&2; exit 1; }
	sleep 0.1
	i=$((i + 1))
done
