#!/bin/sh
# file-preseed runs after the USB is mounted and before account or disk setup.
set -eu
. /usr/lib/newworld-installer/mode
ensure_normal_install
. /usr/share/debconf/confmodule
root=/usr/lib/newworld-installer
state=/run/newworld-install
mkdir -p "$state"
chmod 700 "$state"
/usr/lib/newworld-installer/usb-log start >/dev/null 2>&1 || true
/usr/lib/newworld-installer/usb-log event waiting 0 >/dev/null 2>&1 || true
trap 'result=$?; if [ "$result" -ne 0 ]; then echo "Could not register the names with the installer. Installation stopped." >"$state/error"; logger -t newworld "Names hook failed with status $result"; /usr/lib/newworld-installer/usb-log finish failed >/dev/null 2>&1 || true; while :; do sleep 60; done; fi' EXIT
if [ ! -s "$state/decision" ]; then
    touch "$state/names-ready"
    udevadm settle || true
    if [ -S /tmp/.X11-unix/X0 ]; then
        DISPLAY=:0 setxkbmap -layout us,il -option grp:alt_shift_toggle || true
    fi
    if [ -S /tmp/.X11-unix/X0 ]; then
        DISPLAY=:0 "$root/python" "$root/names.py" </dev/null >"$state/screen.log" 2>&1 3>&- 4>&- &
    else
        "$root/python" "$root/names.py" --text </dev/tty >/dev/tty 2>"$state/screen.log" 3>&- 4>&- &
    fi
    screen_pid=$!
    while [ ! -s "$state/decision" ]; do
        if ! kill -0 "$screen_pid" 2>/dev/null; then
            logger -t newworld 'Names screen ended without disk authorization; setup stopped'
            while :; do sleep 60; done
        fi
        sleep 1
    done
fi
# file-preseed runs before user-setup/netcfg udebs have loaded all of their
# templates. The stock selection loader registers the typed values immediately.
{
    printf 'd-i passwd/user-fullname string %s\n' "$(cat "$state/display")"
    printf 'd-i passwd/username string %s\n' "$(cat "$state/login")"
    printf 'd-i netcfg/get_hostname string %s\n' "$(cat "$state/hostname")"
    printf 'd-i netcfg/hostname string %s\n' "$(cat "$state/hostname")"
    printf '%s\n' 'd-i passwd/user-password-crypted password !' 'd-i passwd/root-login boolean false'
} >"$state/collect-names.selections"
debconf-set-selections "$state/collect-names.selections"
db_get passwd/username
[ "$RET" = "$(cat "$state/login")" ]
logger -t newworld 'Names confirmed by customer; immutable disk selection recorded'
