#!/bin/sh
# SPDX-License-Identifier: MIT
# Copyright (C) 2026 pake <pake@fedora.tw> - https://pomelo-os.org
# desk-rescue REASON: text console login (docs/LOGIN.md).  Used when the desktop could not start (desk-session "give up") and for
# the kernel command line word  rescue=1  (forgotten password: whoever can edit the boot command line has the machine; no password).
#   - REASON starting with "rescue=1": a root shell at once, with the commands that reset a password.
#   - otherwise: asks for the name and password of an ADMINISTRATOR account (checked against the account store), then a root shell.
#     Without any account (setup not finished) it is a plain root shell.
PATH=/usr/bin:/bin:/sbin:/usr/sbin
exec </dev/console >/dev/console 2>&1
case "$1" in rescue=1*) MODE=cmdline;; *) MODE=login;; esac
echo
echo "================ Pomelo rescue console ($1) ================"
if [ "$MODE" = cmdline ] || [ "$(pomelo-accounts count 2>/dev/null)" = 0 ]; then
    echo "root shell.  Accounts:  pomelo-accounts list"
    echo "Set a new password:     echo 'NEWPASSWORD' | pomelo-accounts passwd NAME"
    echo "Make an account admin:  pomelo-accounts admin NAME on"
    echo "Continue booting:       exit   (the normal start follows when this was rescue=1: remove it from the command line afterwards)"
    /bin/sh
    exit 0
fi
printf 'administrator name: '; read u
stty -echo 2>/dev/null; printf 'password: '; read p; stty echo 2>/dev/null; echo
if printf '%s\n' "$p" | pomelo-accounts verify "$u" && pomelo-accounts list | awk -v u="$u" '$1==u && $3=="admin"{f=1} END{exit !f}'; then
    echo "welcome $u (root shell)"
    /bin/sh
else
    echo "wrong name or password, or not an administrator"; sleep 3
fi
exit 0
