#!/bin/sh
# Starchaser owns crash notices for this window.
export QS_DISABLE_CRASH_HANDLER=1 STARCHASER_QML_APP=lock
# summary: Lock this desktop session.
# Lock the session with the Starchaser lock screen (Quickshell, ~/.config/quickshell/lock). One instance:
# if it's already up this does nothing. Used by Super+L, the idle timer (hypridle lock_cmd) and before sleep.
#
# Run from a systemd service (the screensaver's "lock after" timer runs `starchaser power idle ... lock` as a
# short-lived transient service), everything started here sits in that service's cgroup, and systemd kills the
# whole cgroup the moment the service's main process ends: setsid doesn't leave it. The screensaver stopped, no
# lock came up, and the screensaver started again a minute later. So there: ignore the stop signal until the
# lock screen has been handed to a scope of its own (detach below), which the service ending can't touch.
INUNIT=
if grep -q '\.service$' /proc/self/cgroup 2>/dev/null; then INUNIT=1; trap '' TERM; fi
case "${1:-}" in
    -h|--help|help)
        [ $# -eq 1 ] || { echo "Usage: starchaser lock" >&2; exit 2; }
        echo "Usage: starchaser lock"; echo; echo "Locks the screen (the same as Super+L)."; exit 0 ;;
esac
if [ $# -gt 0 ]; then
    case "$1" in
        -*) echo "starchaser lock: unknown option '$1'" >&2
            echo "Run 'starchaser lock --help' for more help." >&2 ;;
        *)  echo "starchaser lock: unexpected argument '$1' (it takes none)" >&2
            echo "Run 'starchaser lock --help' for more help." >&2 ;;
    esac
    echo "Usage: starchaser lock" >&2
    exit 2
fi
# Help belongs to the visible, unlocked desktop. Revoke it before that indicator is covered.
# The normal lock path and the fallback lock both pass here; previews do not call this script. The watcher and the
# backup lock's waiter (this script again, started once the screen is locked) don't: help already ended then.
if [ -z "${STARCHASER_LOCK_WATCH:-}${STARCHASER_LOCK_UNLOCK_WAIT:-}" ] && command -v starchaser >/dev/null 2>&1; then
    timeout 8 starchaser link end-help >/dev/null 2>&1 || true
fi
# The lock screen's own messages (a QML or import error after an update) go to a log, not nowhere.
LOGDIR="${XDG_STATE_HOME:-$HOME/.local/state}/starchaser"
mkdir -p "$LOGDIR" 2>/dev/null
LOG="$LOGDIR/lock.log"
[ -f "$LOG" ] && [ "$(wc -c <"$LOG" 2>/dev/null || echo 0)" -gt 262144 ] && mv -f "$LOG" "$LOG.old" 2>/dev/null
# a log that can't be opened (the folder is writable but lock.log itself isn't, say it was made by root) made every
# `>>"$LOG"` below fail, and with it the start of both lock screens: the desktop stayed open
# (probed in a subshell: in sh, a failed redirection on the `:` builtin ends the whole script, so `|| LOG=/dev/null`
# never ran and nothing locked)
( : >>"$LOG" ) 2>/dev/null || LOG=/dev/null
# Start the lock screen so it outlives whoever asked for it (see the top). The lock screen itself gets the
# normal stop signal back (env --default-signal), so logging out still ends it.
detach() {
    if [ -n "$INUNIT" ]; then
        command -v systemd-run >/dev/null 2>&1 &&
            systemd-run --user --scope --collect --quiet -- env --default-signal=TERM setsid -f "$@" >>"$LOG" 2>&1 &&
            return 0
        env --default-signal=TERM setsid -f "$@" >>"$LOG" 2>&1
        return
    fi
    setsid -f "$@" >>"$LOG" 2>&1
}
# The plain backup lock: used when the Starchaser lock screen isn't installed or doesn't come up. A desktop left
# open is never the answer (a laptop would sleep and wake unlocked).
# Only this account's hyprlock counts: another person's (a second login on another screen) locks nothing here.
ME=$(id -u)
own_hyprlock() { pgrep -u "$ME" -x hyprlock >/dev/null 2>&1; }
# hyprlock with no config of its own exits at once (nothing locked), and a fresh account has none: unless the person
# made ~/.config/hypr/hyprlock.conf, it gets a plain one written here (a dark screen, a password box, two lines).
# Its password check is Starchaser's own when installed: the distro's stack locked the account (sign-in and sudo
# too) for 10 minutes after 3 typos, against the lock screen's rule (decided 2026-10-08), and why showed for 2 s.
# Starchaser's has the lock screen's growing waits instead, and never locks the account.
BACKUP_PAM=/usr/lib/pam.d/starchaser-backup-lock
# a size or offset in the plain lock's config, at Settings > Accessibility's text size (1, 1.25, 1.5 or 2; else 1)
px() { awk -v n="$1" -v s="${text_scale:-1}" 'BEGIN { if (s != 1.25 && s != 1.5 && s != 2) s = 1; printf "%d", n * s + (n < 0 ? -0.5 : 0.5) }'; }
# one line of the help under the password box (line 0 first). hyprlock doesn't wrap, so each line stays short
# enough for a 1280-pixel-wide screen at the largest text size.
help_label() {
    printf 'label {\n    monitor =\n    text = %s\n    color = rgba(180, 180, 200, 1.0)\n    font_size = %s\n    position = 0, %s\n    halign = center\n    valign = center\n}\n' \
        "$2" "$(px 13)" "$(px $((-70 - 22 * $1)))"
}
backup_lock() {
    own_hyprlock && return 0
    text_scale=$(sed -n 's/.*"text_scale"[[:space:]]*:[[:space:]]*\([0-9.]*\).*/\1/p' \
        "${XDG_CONFIG_HOME:-$HOME/.config}/starchaser/accessibility.json" 2>/dev/null | head -n 1)
    conf="${XDG_CONFIG_HOME:-$HOME/.config}/hypr/hyprlock.conf"
    if [ ! -r "$conf" ]; then
        # the private runtime folder; without one, a file only this account can open (a fixed name in /tmp could be
        # made beforehand by someone else)
        if [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -d "$XDG_RUNTIME_DIR" ]; then
            conf="$XDG_RUNTIME_DIR/starchaser-hyprlock.conf"
            rm -f "$conf" 2>/dev/null
        else
            conf=$(umask 077; mktemp /tmp/starchaser-hyprlock-XXXXXX 2>/dev/null) || conf=/dev/null
        fi
        # a restart by the power button is a power loss, and automatic sign-in still opens the desktop after one: the
        # help says how to reach sign-in from there too, as the main lock screen's does
        [ "$conf" = /dev/null ] || { (umask 077; cat >"$conf") <<CONF
background {
    monitor =
    color = rgba(14, 12, 28, 1.0)
}
label {
    monitor =
    text = Locked. Type your password and press Enter.
    color = rgba(230, 230, 240, 1.0)
    font_size = $(px 18)
    position = 0, $(px 90)
    halign = center
    valign = center
}
input-field {
    monitor =
    size = $(px 320), $(px 52)
    fade_on_empty = false
    placeholder_text = Password
    position = 0, 0
    halign = center
    valign = center
    fail_timeout = 10000
}
$(help_label 0 "Forgot your password? Restart the computer,")
$(help_label 1 "then choose Can't sign in? on the sign-in screen.")
$(help_label 2 "If automatic sign-in opens the desktop instead, open the main menu,")
$(help_label 3 "choose Power, then Sign out, and choose Can't sign in? there.")
CONF
        # Starchaser's own check also has the lock screen's waits (starchaser-lock-wait), said here so a wait of up
        # to 90 s after Enter isn't taken for a hang
        [ ! -r "$BACKUP_PAM" ] || { printf 'auth {\n    pam:module = %s\n}\n' "${BACKUP_PAM##*/}"
            help_label 4 "After 5 wrong tries in a row, each wrong try makes you wait:"
            help_label 5 "30 seconds, then 60, then 90."; } >>"$conf"
        } 2>/dev/null || conf=""
        if [ "$conf" = /dev/null ]; then conf=""; fi
    fi
    # A clean backup-lock exit means a real unlock. A crash must keep notification speech private.
    guard='hyprlock "$@"; status=$?; if [ "$status" = 0 ]; then timeout 2 qs -p "$HOME/.config/quickshell/cockpit" ipc call cockpit lockState false >/dev/null 2>&1 || true; fi; exit "$status"'
    if [ -n "$conf" ]; then detach sh -c "$guard" sh -c "$conf"; else detach sh -c "$guard" sh; fi
}
# Satellites' lock actions, once the screen really is locked. They can't draw on the lock screen; they only run
# scripts. detach: from a service, its own scope, so the service ending doesn't stop them; they never hold this up.
# A lock screen the watcher brings back after a crash is the same lock: no second lock event (LOCK_AGAIN below).
satellite_lock_hook() {
    [ -n "$LOCK_AGAIN" ] && return 0
    command -v starchaser >/dev/null 2>&1 && detach starchaser satellite hook lock --wait
    return 0
}
# The backup lock's own unlock writes nothing, so its unlock event comes from a small waiter: once this account's
# backup lock has come up and gone again, while the desktop is still there, the unlock actions run. One waiter.
satellite_backup_unlock_hook() {
    command -v starchaser >/dev/null 2>&1 && detach env STARCHASER_LOCK_UNLOCK_WAIT=1 "$SELF"
    return 0
}
CFG="$HOME/.config/quickshell/lock"
RUN=${XDG_RUNTIME_DIR:-/tmp}
# Written by the lock screen just before it really unlocks (lock/shell.qml unlock()): the watcher below stops there.
UNLOCKED="$RUN/starchaser-lock.unlocked"
# Written by the lock screen (its pid) once the compositor says every screen is covered, removed as it unlocks: the
# wait below looks at this file and asks the lock screen itself only once it is there.
SECURE="$RUN/starchaser-lock.secure"

# The watcher: started once the lock screen holds the screens. If the lock screen program ends while still locked
# (a crash, or something killed it), the session stays locked but Hyprland draws its own error page (with its
# name and terminal commands on it) until a new lock screen starts, and nothing started one. This brings a new one
# up within a few seconds. It stops when the lock screen says it unlocked, when the plainer backup lock takes over
# (its own unlock writes nothing, so a gone backup lock can't be told from an unlock), or when the desktop session
# is gone (logging out must never lead to a lock). One watcher per account (flock). It never touches the pointer.
lock_procs() {      # this account's lock screen processes (not a preview window, not a short `ipc` question)
    pgrep -u "$ME" -a -f "qs -p $CFG" 2>/dev/null | grep -v ' ipc ' | while read -r pid _; do
        tr '\0' '\n' <"/proc/$pid/environ" 2>/dev/null | grep -qx STARCHASER_LOCK_PREVIEW=1 || echo "$pid"
    done
}
# The session's own compositor, not just its socket: a Hyprland that crashed leaves its socket file behind, and a
# watcher that went on would start lock screens into the next login (which can reuse the same display name).
# Hyprland's hyprland.lock holds its pid on the first line.
HYPR_PID=
[ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] &&
    read -r HYPR_PID 2>/dev/null <"$RUN/hypr/$HYPRLAND_INSTANCE_SIGNATURE/hyprland.lock"
case $HYPR_PID in *[!0-9]*) HYPR_PID= ;; esac
session_alive() {
    if [ -n "$HYPR_PID" ]; then
        comm= && read -r comm 2>/dev/null <"/proc/$HYPR_PID/comm"
        case $comm in *[Hh][Yy][Pp][Rr][Ll][Aa][Nn][Dd]*) ;; *) return 1 ;; esac
        [ -S "$RUN/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket.sock" ]
    elif [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ]; then
        [ -S "$RUN/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket.sock" ] && pgrep -u "$ME" -i -x hyprland >/dev/null 2>&1
    else
        pgrep -u "$ME" -i -x hyprland >/dev/null 2>&1
    fi
}
watch_lock() {
    exec 9>"$RUN/starchaser-lock.watch" || exit 0
    # a short wait: after an unlock and a quick lock again, the last watcher may still be on its way out
    flock -w 2 9 || exit 0
    gone=0 starts=""
    while :; do
        sleep 0.5
        [ -e "$UNLOCKED" ] && exit 0
        session_alive || exit 0
        own_hyprlock && exit 0
        pids=$(lock_procs)
        if [ -n "$pids" ]; then
            gone=0
            # The lock screen is up: one waiting program (tail --pid) until it ends, and at least every 5 minutes
            # the looks above (the unlock mark, the session). Looking with pgrep every half second started about
            # 1000 programs a minute on a locked screen. An unlock, the backup lock taking over and the session
            # ending all end this lock screen first, so none is missed while waiting: the timeout is only a backstop.
            # shellcheck disable=SC2086
            set -- $pids
            timeout 300 tail --pid="$1" -f /dev/null 9>&- 2>/dev/null    # (never holding the watcher lock)
            continue
        fi
        # about 2.5 s with no lock screen: the lock screen's own restart after a text screen (lock/shell.qml)
        # takes up to about 2 s, and it should win; this is for when nothing else is bringing one back
        gone=$((gone + 1)); [ "$gone" -ge 5 ] || continue
        gone=0
        now=$(date +%s) recent=""
        for t in $starts; do [ $((now - t)) -lt 60 ] && recent="$recent $t"; done
        starts="$recent $now"
        set -- $starts
        if [ $# -gt 5 ]; then           # keeps dying: the plainer lock, so the session is never left on the error page
            echo "$(date '+%F %T') the lock screen keeps stopping; using the backup lock" >>"$LOG"
            backup_lock
            satellite_backup_unlock_hook
            exit 0
        fi
        echo "$(date '+%F %T') the lock screen stopped while locked; starting it again" >>"$LOG"
        STARCHASER_LOCK_AGAIN=1 "$SELF" 9>&-
    done
}
SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
# set by the watcher when it starts the lock screen again; not handed on to the lock screen itself
LOCK_AGAIN=${STARCHASER_LOCK_AGAIN:-}
unset STARCHASER_LOCK_AGAIN

if [ "${STARCHASER_LOCK_UNLOCK_WAIT:-}" = 1 ]; then
    unset STARCHASER_LOCK_UNLOCK_WAIT
    exec 8>"$RUN/starchaser-lock.unlock-wait" || exit 0
    flock -n 8 || exit 0
    i=0
    while [ $i -lt 20 ] && ! own_hyprlock; do sleep 0.25; i=$((i + 1)); done
    own_hyprlock || exit 0
    while own_hyprlock; do sleep 1; done
    session_alive && starchaser satellite hook unlock 8>&-
    exit 0
fi
if [ "${STARCHASER_LOCK_WATCH:-}" = 1 ]; then
    unset STARCHASER_LOCK_WATCH         # or the lock it starts again would be another watcher
    [ -f "$CFG/shell.qml" ] && watch_lock
    exit 0
fi
if [ ! -f "$CFG/shell.qml" ]; then          # not installed on this machine yet: never leave it unlockable
    own_hyprlock && exit 0                  # already locked: no second lock event
    backup_lock
    satellite_lock_hook
    satellite_backup_unlock_hook
    exit 0
fi
# Locked only when a real lock screen says `true` (the call exits 0 whatever it answers, so the exit code says
# nothing). A preview window answers false. `ipc` talks to the oldest copy of this config by default, so with a
# preview window open the real lock is the newest one: ask both.
# Only the answer's last line counts: with no UTF-8 locale (a service or an SSH session with LANG unset) qs prints a
# locale warning on standard output before the answer, "true" never matched, and a lock screen that was up got the
# backup lock started over it and a "didn't start" notice.
ask_lock() {        # $1: seconds to wait, then the ipc arguments
    t=$1; shift
    timeout "$t" qs "$@" 2>/dev/null | tail -n 1
}
is_locked() {
    own_hyprlock && return 0
    [ "$(ask_lock "${1:-3}" -p "$CFG" ipc call -- lock locked)" = true ] && return 0
    [ "$(ask_lock "${1:-3}" ipc --newest -p "$CFG" call -- lock locked)" = true ]
}
is_locked && exit 0
# Just after an unlock the old lock screen is still alive for about 300 ms (lock/shell.qml quits then): it already
# answers "not locked", but `qs -n` below would refuse to start beside it, and its detached "unlocked" mark could
# land after the rm below and make this run think it was unlocked already. Either way nothing locked. So: wait (up
# to about 1.5 s) for a lock screen on its way out to be gone, then ask again. A lock screen still starting (two
# requests at once) answers true by then, and this run stops there.
if [ -n "$(lock_procs)" ]; then
    i=0
    while [ $i -lt 6 ] && [ -n "$(lock_procs)" ]; do sleep 0.25; i=$((i + 1)); done
    is_locked 2 && exit 0
fi
# Who asked for the lock (Super+L, the idle timer's listener, the menu, a service): the names of the processes
# behind this one, so a lock screen that appears on its own can be traced in this log. Read with shell builtins
# (/proc/PID/status: Name, then PPid): a cat, ps and tr for each of them was most of the programs a lock started.
asked= p=$PPID
while [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && [ "${#asked}" -lt 60 ]; do
    name= next=
    while read -r key value _; do
        case $key in Name:) name=$value ;; PPid:) next=$value; break ;; esac
    done 2>/dev/null <"/proc/$p/status" || break
    asked="$asked$name "
    p=$next
done
echo "$(date '+%F %T') starting the lock screen (asked by: ${asked% })" >>"$LOG"
# Hold notification cards and speech before either lock screen can acquire the screens.
timeout 2 qs -p "$HOME/.config/quickshell/cockpit" ipc call cockpit locked >/dev/null 2>&1 || true
# Before the lock screen starts, never after: removed later, it could erase the mark of a quick real unlock and
# the watcher would lock the desktop again.
rm -f "$UNLOCKED" "$SECURE"
# -n: never a second copy, so two lock requests at once start one lock screen. A preview window open is a copy too
# and would block the real one, so then it starts without -n.
if [ "$(ask_lock 3 -p "$CFG" ipc call -- lock preview)" = true ]; then
    detach qs -p "$CFG"
else
    detach qs -p "$CFG" -n
    # refused at once (an old copy still hadn't gone): one more try a moment later
    sleep 0.5
    if [ -z "$(lock_procs)" ] && [ ! -e "$UNLOCKED" ]; then
        echo "$(date '+%F %T') the lock screen didn't start; trying once more" >>"$LOG"
        detach qs -p "$CFG" -n
    fi
fi
# setsid returns as soon as it forks, so a lock screen that fails to load would leave the desktop open with no
# word to anyone: wait up to about 6 seconds for it to say it really holds the screens. The wait looks at the lock
# screen's mark ($SECURE, no program started) and asks it (is_locked, up to seven programs) only once the mark is
# there, at most three times, then once more at the end for a lock screen that leaves no mark. A bounded number of
# short questions keeps the whole wait bounded, even when the lock screen is slow to answer each one.
exit_if_locked() {
    if is_locked 2; then
        own_hyprlock || detach env STARCHASER_LOCK_WATCH=1 "$SELF"
        satellite_lock_hook
        exit 0
    fi
}
i=0 asks=0
while [ $i -lt 24 ] && [ $asks -lt 3 ]; do
    sleep 0.25
    i=$((i + 1))
    # unlocked already (a quick password while a question above was slow to answer): it came up and did its job,
    # so no backup lock and no "didn't start" notice
    [ -e "$UNLOCKED" ] && exit 0
    [ -e "$SECURE" ] || continue
    asks=$((asks + 1))
    exit_if_locked
done
[ -e "$UNLOCKED" ] && exit 0
exit_if_locked
echo "$(date '+%F %T') the lock screen didn't come up; using the backup lock" >>"$LOG"
backup_lock
# The notice comes once the backup lock is up, so it waits behind the lock for after unlocking (sent at once, it
# popped up over the still-open desktop): wait up to 5 s for hyprlock to run, then a moment for it to draw.
i=0
while [ $i -lt 20 ] && ! own_hyprlock; do sleep 0.25; i=$((i + 1)); done
# satellites hear about the lock only once the backup lock really is up
if own_hyprlock; then
    satellite_lock_hook
    satellite_backup_unlock_hook
else
    # No lock acquired, so logind need not emit any change. Re-read its state rather than leaving the
    # taskbar's pre-launch privacy hold latched, or optimistically claiming the session is unlocked.
    timeout 2 qs -p "$HOME/.config/quickshell/cockpit" ipc call cockpit refreshLock >/dev/null 2>&1 || true
    command -v notify-send >/dev/null 2>&1 &&
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical -i system-lock-screen "Couldn't lock the computer" \
            "Both lock screens failed to start. Stay with the computer and try locking again. Details: ~/.local/state/starchaser/lock.log" \
            >/dev/null 2>&1
    exit 1
fi
sleep 1
command -v notify-send >/dev/null 2>&1 &&
    /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical -i system-lock-screen "Locked with the backup lock screen" \
        "The usual lock screen didn't start, so a plainer one locked the computer. Details: ~/.local/state/starchaser/lock.log" \
        >/dev/null 2>&1 &
exit 0
