#!/usr/bin/env bash
#
# Stage the bundled Linux kernel that ContainerEngine boots its VMs from.
#
#   scripts/fetch-kernel.sh
#
# The kernel is the ONE container-runtime asset shipped in the app (it's stable and rarely
# changes). Everything else is pulled at runtime: the vminitd initfs (ghcr apple/containerization)
# and the sandbox image (our registry — see containers/nucleic-sandbox/). So this needs NO build
# toolchain — just curl + tar. Output:
#
#   Resources/vmlinux-arm64   uncompressed arm64 Linux kernel (Kata-static, VZ-compatible)
#
# package-app.sh copies it into the .app bundle; for a `swift run` dev build, point
# NUCLEIC_KERNEL_PATH at it (or reuse Apple `container`'s kernel if you have the CLI installed).

set -euo pipefail

# Kata static release providing a VZ-compatible vmlinux.container (kernel ≥ 6.12). Matches the
# version apple/containerization's `make fetch-default-kernel` uses; bump deliberately.
KATA_VERSION="3.17.0"
KATA_URL="https://github.com/kata-containers/kata-containers/releases/download/${KATA_VERSION}/kata-static-${KATA_VERSION}-arm64.tar.xz"

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
RES="$ROOT/Resources"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

mkdir -p "$RES"

echo "▸ Downloading Kata static ${KATA_VERSION} (arm64) …"
curl -SsL -o "$TMP/kata.tar.xz" "$KATA_URL"

echo "▸ Extracting kernel from opt/kata/share/kata-containers …"
# bsdtar on macOS handles .xz. Extract the WHOLE kernel directory, not just `vmlinux.container`:
# in kata-static that name is a SYMLINK to a versioned `vmlinux-<ver>.container`, so pulling only the
# symlink member leaves a dangling link and the real kernel never lands on disk. Try the archive's
# `./`-prefixed and bare member paths; last resort, extract everything.
tar -xJf "$TMP/kata.tar.xz" -C "$TMP" "./opt/kata/share/kata-containers" 2>/dev/null \
    || tar -xJf "$TMP/kata.tar.xz" -C "$TMP" "opt/kata/share/kata-containers" 2>/dev/null \
    || tar -xJf "$TMP/kata.tar.xz" -C "$TMP"

KDIR="$TMP/opt/kata/share/kata-containers"

# Resolve the plain (non-confidential / non-GPU) uncompressed kernel. Prefer following the
# `vmlinux.container` symlink to its versioned target (readlink without -f → portable on macOS, the
# target is relative within the same dir); else take the newest matching versioned file.
SRC=""
if [ -L "$KDIR/vmlinux.container" ]; then
    tgt="$(readlink "$KDIR/vmlinux.container")"
    case "$tgt" in /*) SRC="$tgt" ;; *) SRC="$KDIR/$tgt" ;; esac
elif [ -f "$KDIR/vmlinux.container" ]; then
    SRC="$KDIR/vmlinux.container"            # older layout: already a regular file
fi
if [ -z "$SRC" ] || [ ! -f "$SRC" ]; then
    SRC="$(find "$KDIR" -maxdepth 1 -type f -name 'vmlinux-*.container' \
        ! -name '*confidential*' ! -name '*nvidia*' ! -name '*gpu*' 2>/dev/null | sort | tail -1)"
fi
if [ -z "$SRC" ] || [ ! -f "$SRC" ]; then
    echo "vmlinux kernel not found in archive. vmlinux* entries present:" >&2
    tar -tJf "$TMP/kata.tar.xz" 2>/dev/null | grep -i vmlinu >&2 || echo "  (none — bad/partial download?)" >&2
    exit 1
fi
cp "$SRC" "$RES/vmlinux-arm64"

echo "✓ Staged $RES/vmlinux-arm64 ($(du -h "$RES/vmlinux-arm64" | cut -f1))"
echo "  Bundled into the .app by scripts/package-app.sh."
echo "  For \`swift run\`: export NUCLEIC_KERNEL_PATH=\"$RES/vmlinux-arm64\""
