#!/bin/sh
# felhom-bootstrap postinst.
#
# THIS SCRIPT MUST NOT BE ABLE TO FAIL. It runs under `dpkg --configure -a` INSIDE THE PVE INSTALLER
# CHROOT, in the middle of a customer's installation. A non-zero exit surfaces to that customer as an
# install error — far worse than the bootstrap simply not running. The stub not running costs one
# documented command; a broken install costs the machine.
#
# Four constraints, every one MEASURED in SPIKE-universal-iso-4-2026-07-31.md §3:
#   1. NO `set -e`            — it converts any unexpected non-zero into the failure above.
#   2. NO systemctl start / daemon-reload — pid1 in the chroot is `unconfigured.sh` and NO systemd is
#                               running; those verbs are meaningless there. `enable` is the only one
#                               that works, and it was measured to work (it wrote the symlink).
#   3. NO network use         — the network was up in the probe ONLY because the installer's DHCP
#                               happened to hold. A box installed with the cable out has none.
#   4. Real work at first boot — the unit does it, where systemd, network and a booted kernel exist.
#
# Every statement below is therefore individually guarded and the script ends `exit 0` unconditionally.

UNIT=felhom-bootstrap.service
LOG=/var/log/felhom-bootstrap-postinst.log

# A positive observable that this ran. SPIKE 2 R-150: a hook that never ran is indistinguishable from
# one that succeeded if you only look for errors.
{
    echo "felhom-bootstrap postinst: arg1=${1:-} date=$(date -u -Is 2>/dev/null || echo unknown)"
} >> "$LOG" 2>&1 || true
chmod 0644 "$LOG" 2>/dev/null || true

if [ "${1:-}" = "configure" ]; then
    # `enable` only. Guarded, and its outcome recorded either way.
    if systemctl enable "$UNIT" >> "$LOG" 2>&1; then
        echo "felhom-bootstrap postinst: enabled $UNIT via systemctl" >> "$LOG" 2>&1 || true
    else
        # Fallback: write the wants-symlink by hand. Also guarded — if this fails too, the unit is
        # simply not enabled and the operator runs the documented one-liner. The install still succeeds.
        mkdir -p /etc/systemd/system/multi-user.target.wants 2>/dev/null || true
        ln -sf "/lib/systemd/system/$UNIT" \
               "/etc/systemd/system/multi-user.target.wants/$UNIT" 2>/dev/null || true
        echo "felhom-bootstrap postinst: systemctl enable failed; wrote wants-symlink by hand" \
            >> "$LOG" 2>&1 || true
    fi
fi

exit 0
