#!/bin/sh
# amadeOS screen lock. Keeps the screen locked even if the lock process crashes or is killed:
# only a successful unlock (exit 0) ends the loop.
set -u

# The lock is in the amadeos-session jar; AMADEOS_JAR lets the tests run it from their class path.
AMADEOS_JAR="${AMADEOS_JAR:-/opt/amadeos-session/amadeos-session.jar}"
if [ -n "${JAVA_HOME:-}" ] && [ -x "$JAVA_HOME/bin/java" ]; then
    JAVA_BIN="$JAVA_HOME/bin/java"
elif [ -x /usr/lib/jvm/java-25-openjdk-amd64/bin/java ]; then
    JAVA_BIN=/usr/lib/jvm/java-25-openjdk-amd64/bin/java
else
    JAVA_BIN="$(command -v java)"
fi

grab_failures=0
crashes=0
while :; do
    "$JAVA_BIN" --enable-native-access=ALL-UNNAMED -cp "$AMADEOS_JAR" eu.amadeos.system.lock.ScreenLock
    rc=$?
    case "$rc" in
        0) exit 0 ;;                  # unlocked with the correct password
        3) exit 0 ;;                  # another lock process already holds the screen
        5) exit 5 ;;                  # X display gone (session ended)
        126|127) exit "$rc" ;;        # Java not installed or not executable
        4)                            # input grabbed by another client (e.g. an open menu)
            grab_failures=$((grab_failures + 1))
            [ "$grab_failures" -ge 5 ] && exit 4
            sleep 1 ;;
        *)                            # crashed or killed: lock again immediately
            crashes=$((crashes + 1))
            echo "[amadeos-lock] lock process ended with $rc, locking again" >&2
            # Back off a little if it keeps failing, but never give up and leave the screen open.
            if [ "$crashes" -ge 10 ]; then sleep 2; else sleep 0.2; fi ;;
    esac
done
