#!/bin/bash
# Phase-2 first-boot provisioning for the naros-vm (docs/NAROS.md §7.4, milestones N4/N5).
#
# Runs ONCE, as root, from `nucleic-firstboot.service` the first time the installed naros rootfs
# boots. Behavior is FLAVOR-driven (from /etc/naros/manifest.json):
#   • headless (N4): the rootfs is naros base + the vsock agent + systemd; firstboot `apt install`s
#     the naros-tier-vm meta from the hosted repo (sudoers, dbus, tier), then writes readiness.
#   • desktop  (N5): GNOME 50 + the tier are BAKED into the forky rootfs at build time (the
#     naros-desktop-config postinst already ran), so firstboot only writes readiness.
# nash is ALREADY the forced shell either way (the divert is baked), and the vsock control-plane
# agent is already up (its deb is baked into BOTH rootfs flavors and ships its own enable symlink —
# nothing here installs it), so the host can poll the readiness flag.
#
# The guest is a disposable, NAT-isolated VM; provisioning is unattended.
set -x
exec >>/var/log/nucleic-provision.log 2>&1
export DEBIAN_FRONTEND=noninteractive

log() { echo "[naros-provision $(date -u +%H:%M:%S)] $*"; }
progress() { echo "$*" > /var/lib/nucleic/progress; }   # tail'd by the host for a live sub-step

mkdir -p /var/lib/nucleic

# Flavor decides whether firstboot installs anything. The desktop rootfs bakes GNOME + the tier
# at build time, so it has nothing to pull; the headless rootfs pulls its tier from the hosted repo.
flavor="$(sed -n 's/.*"flavor" *: *"\([^"]*\)".*/\1/p' /etc/naros/manifest.json 2>/dev/null)"

if [ "$flavor" = desktop ]; then
    log "desktop flavor — GNOME + naros-tier-vm-desktop baked at build time; nothing to install"
    progress "Finalizing the desktop"
else
    # Wait for NAT DHCP so the hosted apt repo resolves (naros-keyring ships the source entry).
    log "waiting for network"
    progress "Waiting for network"
    for i in $(seq 1 60); do
        getent hosts apt.naros.nucleic.blakeslee.xyz >/dev/null 2>&1 && break
        sleep 2
    done
    # The one substantive step: pull the VM tier (vsock agent, sudoers, systemd/dbus). Everything
    # the old provisioner did by hand now lives in the meta-package's dependency graph (§7.4).
    log "installing the naros-vm tier (apt install naros-tier-vm)"
    progress "Installing the naros-vm tier"
    apt-get update -y || true
    apt-get install -y naros-tier-vm || log "WARN: naros-tier-vm install failed (is the hosted apt repo live?)"
fi

# Seal: stop re-running, reclaim space, signal readiness (the host's gate before it powers off).
log "sealing the base"
progress "Finalizing"
systemctl disable nucleic-firstboot.service 2>/dev/null || true
apt-get clean || true
sync
touch /var/lib/nucleic/provisioned
log "provisioning complete"
