#!/usr/bin/env bash
# Build the phase-1 **bootstrap initramfs** for the Nucleic Linux base build (docs/LINUX_VM.md).
#
# The bootstrap is a tiny busybox initramfs whose `/init` (guest/linux-base/bootstrap/init) formats the
# raw root disk, unpacks the Ubuntu rootfs handed in over virtiofs, and bakes in the Nucleic agent —
# the in-guest half of "assemble a Linux rootfs from macOS, which has no Linux FS tools."
#
# Portable by design: it needs only a static busybox (downloaded), plus `ar`, `tar`, `gzip`, and
# `python3` — all present in the Nucleic Linux build container AND on a dev Mac with the Xcode command
# line tools. The Swift engine invokes this at base-build time (or a CI job pre-bakes the output).
#
# Output: a gzipped newc cpio at $OUT (default guest/linux-base/bootstrap/build/nucleic-bootstrap.cpio.gz).
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
init_src="$here/guest/linux-base/bootstrap/init"
out="${OUT:-$here/guest/linux-base/bootstrap/build/nucleic-bootstrap.cpio.gz}"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

# A static arm64 busybox. Overridable (BUSYBOX_DEB_URL) so a pin can move; the default is a Debian
# busybox-static .deb, which carries a single static `/bin/busybox` with the applets /init needs
# (sh, mount, mkfs.ext2, tar, unxz, install, ln, poweroff …).
busybox_deb_url="${BUSYBOX_DEB_URL:-http://ftp.debian.org/debian/pool/main/b/busybox/busybox-static_1.35.0-4+deb12u1+b1_arm64.deb}"

echo "==> fetching static busybox"
if [ -n "${BUSYBOX_BIN:-}" ] && [ -x "${BUSYBOX_BIN}" ]; then
    cp "$BUSYBOX_BIN" "$work/busybox"
else
    curl -fSL "$busybox_deb_url" -o "$work/busybox.deb"
    ( cd "$work" && ar x busybox.deb )
    # data.tar.{xz,gz,zst} — extract whichever is present.
    if [ -f "$work/data.tar.xz" ]; then tar -C "$work" -xJf "$work/data.tar.xz"
    elif [ -f "$work/data.tar.gz" ]; then tar -C "$work" -xzf "$work/data.tar.gz"
    else echo "unexpected .deb layout" >&2; exit 1; fi
    cp "$work/bin/busybox" "$work/busybox"
fi
chmod +x "$work/busybox"

echo "==> laying out the initramfs"
root="$work/root"
mkdir -p "$root/bin" "$root/dev" "$root/proc" "$root/sys" "$root/mnt"
cp "$work/busybox" "$root/bin/busybox"
install -m 0755 "$init_src" "$root/init"
# A /bin/sh so the fail-shell in /init works before `busybox --install`.
ln -sf busybox "$root/bin/sh"

echo "==> packing newc cpio + gzip"
mkdir -p "$(dirname "$out")"
# newc cpio via python3 (no cpio binary needed, and byte-identical on Linux/macOS).
python3 "$here/scripts/lib/mkcpio.py" "$root" | gzip -9 > "$out"

echo "built $out ($(wc -c < "$out") bytes)"
