#!/bin/sh
set -eu
. /usr/lib/newworld-installer/mode
ensure_normal_install
. /usr/share/debconf/confmodule
state=/run/newworld-install
trap 'result=$?; if [ "$result" -ne 0 ]; then echo "Disk preparation stopped." >"$state/error"; logger -t newworld "Disk 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
stop_install() {
    echo 'The selected disk changed. Setup stopped before partitioning.' >"$state/error"
    logger -t newworld 'SAFE STOP: no validated disk selection'
    /usr/lib/newworld-installer/usb-log finish failed >/dev/null 2>&1 || true
    while :; do sleep 60; done
}
[ -s "$state/decision" ] || stop_install
action=$(sed -n '1p' "$state/decision")
token=$(sed -n '2p' "$state/decision")
[ "${#token}" -eq 64 ] || stop_install
case "$token" in *[!0-9a-f]*) stop_install ;; esac
case "$action" in
    erase) set -- --erase ;;
    install) set -- ;;
    *) stop_install ;;
esac
# Bookworm's 1.194 bootloader installer lists every PID under /target/proc
# under set -e. A disappearing PID can make ls abort the entire installation.
# Check the calling process, which exists for the duration of the probe.
grub=/usr/bin/grub-installer
case "$(sha256sum "$grub" | cut -d' ' -f1)" in
    829c507a258ac58a0d32f67e4da059c21c03f498aa6075f1f3d7960451669959)
        sed '/^initial_proc_contents=/d; s/if \[ -z "\$initial_proc_contents" \]; then/if [ ! -r "$ROOT\/proc\/self\/stat" ]; then/' "$grub" >"$state/grub-installer"
        echo "584ca4782655bf8eec3230074d14729457bcb4a767683dc4900da734d2251a37  $state/grub-installer" | sha256sum -c - >/dev/null
        chmod 755 "$state/grub-installer"
        mv "$state/grub-installer" "$grub"
        ;;
    584ca4782655bf8eec3230074d14729457bcb4a767683dc4900da734d2251a37) ;;
    *) exit 1 ;;
esac
target=$(/usr/lib/newworld-installer/install-disk --edition i386 check-token "$token" "$@") || stop_install
[ -b "$target" ] || stop_install
[ "$target" = "$(cat "$state/path")" ] || stop_install
{
    printf 'd-i partman-auto/disk string %s\n' "$target"
    printf 'd-i grub-installer/bootdev string %s\n' "$target"
    printf '%s\n' 'd-i partman-auto/method string regular' 'd-i partman-auto/choose_recipe select atomic' 'd-i partman/choose_partition select finish'
    for key in partman-partitioning/confirm_write_new_label partman/confirm_write_new_label partman/confirm partman/confirm_nooverwrite partman-lvm/device_remove_lvm partman-lvm/confirm partman-lvm/confirm_nooverwrite partman-md/device_remove_md partman-md/confirm grub-installer/only_debian grub-installer/with_other_os; do
        printf 'd-i %s boolean true\n' "$key"
    done
} >"$state/commit-disk.selections"
debconf-set-selections "$state/commit-disk.selections"
db_get partman-auto/disk
[ "$RET" = "$(cat "$state/path")" ]
logger -t newworld "Destination identity revalidated before partitioning: $target"
echo partition >"$state/stage"
