#!/bin/bash -e
# set root password
#
# ROOT_PASS preseeded (or rendered from secrets.root_password by
# 00declarative) sets it without a screen; ROOT_PASS=KEEP keeps the one
# set before the first boot, or fails when Keep would not be offered. Otherwise setpass.py asks, and
# offers to keep a password set before the first boot (pct create
# --password, or LXC in the root file system) when there is one. When
# nobody can answer the console (lib/console.sh), the password stays as
# the machine has it, set before the first boot or locked, as Keep does,
# and the question is recorded for keel-init (console_deferred): the
# first login starts keel-init, which asks it.

USERNAME=root

INITHOOKS_DEFAULT="${INITHOOKS_DEFAULT:-/etc/default/inithooks}"
# shellcheck source=default/inithooks
. "$INITHOOKS_DEFAULT"
[ "$(echo "$SUDOADMIN" | tr '[:upper:]' '[:lower:]')" = "true" ] && USERNAME="admin"

# shellcheck source=lib/console.sh
. "$INITHOOKS_PATH/lib/console.sh"

# shellcheck disable=SC1090
[ -e "$INITHOOKS_CONF" ] && . "$INITHOOKS_CONF"

if [ -z "$ROOT_PASS" ] && console_unattended; then
    console_deferred 30rootpass "the $USERNAME password stays as the machine has it (pct create --password, or locked); keel-init asks it"
    exit 0
fi
"$INITHOOKS_PATH/bin/setpass.py" "$USERNAME" --pass="$ROOT_PASS"
