#!/usr/bin/env bash

# omarchy:summary=Configure Quickshell lock screen authentication
# omarchy:requires-sudo=true
# omarchy:hidden=true

set -e

# Install and upgrade callers can start this helper as root. Ignore their PATH
# so optional commands never fall through to a user-writable directory.
if (( EUID == 0 )); then
  export PATH=/usr/share/omarchy/bin:/usr/local/bin:/usr/bin:/bin
fi

target_user=${OMARCHY_INSTALL_USER:-${SUDO_USER:-}}
if [[ -z $target_user && -n ${PKEXEC_UID:-} ]]; then
  target_user=$(getent passwd "$PKEXEC_UID" | cut -d: -f1)
fi
target_user=${target_user:-$USER}

as_root() {
  if (( EUID == 0 )); then
    "$@"
  else
    sudo "$@"
  fi
}

echo "Configuring lock screen password authentication..."

# Based: Debian's common-auth (pam_unix, and pam_sss for SSSD/Kerberos users)
# and common-account; Debian has no system-local-login. authfail runs inside
# common-auth from the omarchy-shell overlay's omarchy-lock-faillock profile,
# because its requisite pam_deny ends a failed attempt before any later line.
as_root tee /etc/pam.d/omarchy-lock-password >/dev/null <<'EOF'
#%PAM-1.0
auth       required                    pam_faillock.so preauth silent deny=10 unlock_time=120
@include common-auth
auth       required                    pam_env.so
auth       required                    pam_faillock.so authsucc deny=10 unlock_time=120
@include common-account
EOF

if [[ -x /usr/bin/fprintd-list ]] &&
  /usr/bin/fprintd-list "$target_user" 2>/dev/null | grep -qi finger; then
  echo "Configuring lock screen fingerprint authentication..."
  as_root tee /etc/pam.d/omarchy-lock-fingerprint >/dev/null <<'EOF'
#%PAM-1.0
auth       required                    pam_fprintd.so
@include common-account
EOF
else
  as_root rm -f /etc/pam.d/omarchy-lock-fingerprint
fi

# omarchy-shell can't reach a running shell during chroot install. The echo
# is just confirmation, so swallow the failure rather than letting it become
# the script's exit code.
if omarchy-shell lock status >/dev/null 2>&1; then
  echo "Lock screen authentication configured."
fi
