#!/bin/sh
# The backup lock's wrong-password waits (system/usr/lib/pam.d/starchaser-backup-lock runs this through pam_exec, as
# the person signed in): the 5th wrong try in a row waits 30 s, the next 60 s, every one after that 90 s, and the
# right password starts the count over. The account itself is never locked (decided 2026-10-08). The count is the
# main lock screen's own ($XDG_RUNTIME_DIR/starchaser-lock.tries, "tries waitUntilMs": lock/shell.qml), so trading
# one lock for the other neither resets it nor cuts a wait short.
#   wait   before a check: sit out what is left of a wait already running (at most 90 s)
#   fail   after a wrong password: count it, then wait the time it costs
#   ok     after the right password: the count starts over
# Always exits 0: the password check decides, never this.
PATH=${PATH:-/usr/bin:/bin}
# pam_exec passes no XDG_RUNTIME_DIR; the session's private folder is this one, and nothing is kept outside it
RUN=/run/user/$(id -u)
TRIES="$RUN/starchaser-lock.tries"
[ -d "$RUN" ] && [ -O "$RUN" ] || exit 0

now_ms() { date +%s%3N; }
read_tries() {
    tries=0 ends=0
    [ -f "$TRIES" ] && read -r tries ends _ <"$TRIES" 2>/dev/null
    case "$tries" in ''|*[!0-9]*) tries=0 ;; esac
    ends=${ends%%.*}
    case "$ends" in ''|*[!0-9]*) ends=0 ;; esac
    [ "$tries" -le 99 ] || tries=99
}
write_tries() {
    tmp="$RUN/.starchaser-lock.tries.$$.tmp"
    (umask 077; printf '%s %s\n' "$1" "$2" >"$tmp") && mv -f "$tmp" "$TRIES" || rm -f "$tmp"
}
# the seconds left until a given end, never more than the longest wait (a clock that jumped back can't stretch it)
left_s() {
    left=$(( ($1 - $(now_ms) + 999) / 1000 ))
    [ "$left" -le 90 ] || left=90
    [ "$left" -ge 0 ] || left=0
    echo "$left"
}

case "${1:-}" in
    wait)
        read_tries
        [ "$ends" -gt 0 ] && sleep "$(left_s "$ends")"
        ;;
    fail)
        read_tries
        tries=$((tries + 1))
        case "$tries" in 1|2|3|4) wait=0 ;; 5) wait=30 ;; 6) wait=60 ;; *) wait=90 ;; esac
        if [ "$wait" -gt 0 ]; then
            write_tries "$tries" "$(( $(now_ms) + wait * 1000 ))"
            sleep "$wait"
        else
            write_tries "$tries" 0
        fi
        ;;
    ok)
        write_tries 0 0
        ;;
esac
exit 0
