#!/bin/sh
# mmdebstrap customize-hook: stamp narOS identity into the rootfs (NAROS.md §2.3).
# $1 = rootfs dir; NAROS_* env exported by build-rootfs.sh. Debian's own
# /usr/lib/os-release stays intact (ID_LIKE tooling keeps working); we replace only the
# /etc/os-release symlink with the narOS file.
set -eu
R="$1"

# VARIANT is the os-release identity class (base/agent/runner/vm, §2.3); the build passes it
# separately from NAROS_TIER so the two VM flavors (vm, vm-desktop) both report VARIANT=vm and
# carry the headless/desktop distinction in NAROS_FLAVOR. Fallback to the tier for older callers.
VARIANT="${NAROS_VARIANT:-$NAROS_TIER}"
FLAVOR="${NAROS_FLAVOR:-}"
# naros-init/systemd role: the VM tiers boot as a guest (systemd PID 1, §5); everything else is
# a container surface.
case "$VARIANT" in vm) ROLE="vm" ;; *) ROLE="container" ;; esac

# mmdebstrap writes every build source into the target's sources.list — including the
# CI-local [trusted=yes] copy:// pool, which doesn't exist at runtime and would fail
# every `apt update` in a running container. Keep only the real mirrors (the pinned
# snapshot); the hosted Nucleic repo arrives via naros-keyring's sources.list.d entry.
sed -i '\#copy://#d' "$R/etc/apt/sources.list"

rm -f "$R/etc/os-release"
cat > "$R/etc/os-release" <<EOF
NAME="narOS"
PRETTY_NAME="narOS $NAROS_VERSION (Nucleic Agent Runtime OS)"
ID=naros
ID_LIKE=debian
VERSION_ID="$NAROS_VERSION"
VERSION="$NAROS_VERSION ($NAROS_CHANNEL)"
VERSION_CODENAME=$NAROS_SUITE
VARIANT="$VARIANT"
VARIANT_ID=$VARIANT
HOME_URL="https://github.com/abkslm/nucleic"
DOCUMENTATION_URL="https://github.com/abkslm/nucleic/blob/main/docs/NAROS.md"
EOF

mkdir -p "$R/etc/naros"
echo "$NAROS_CHANNEL" > "$R/etc/naros/channel"
echo "$NAROS_SNAPSHOT" > "$R/etc/naros/snapshot-date"
echo "$ROLE" > "$R/etc/naros/role"

# Capability manifest (NAROS.md §6.3). Base fields here; toolchain entries are appended
# by the tiers that install them (agent-tier hook, N2). Versions of Nucleic packages are
# queryable via dpkg, listed here for one-stop reads.
#
# kernel_tag is the suffix naros-identity's preloaded shim appends to uname(2)'s release
# (§2.3) — recorded so a reader can tell the narOS marker apart from the host kernel's own
# version, and strip it. narOS builds no kernel; the tag is identity, not a kernel build.
nash_ver="$(chroot "$R" dpkg-query -W -f '${Version}' nash 2>/dev/null || echo null)"
[ "$nash_ver" = null ] || nash_ver="\"$nash_ver\""
cat > "$R/etc/naros/manifest.json" <<EOF
{
  "os": "naros",
  "version": "$NAROS_VERSION",
  "channel": "$NAROS_CHANNEL",
  "tier": "$NAROS_TIER",
  "variant": "$VARIANT",
  "flavor": "$FLAVOR",
  "arch": "$NAROS_ARCH",
  "kernel_tag": "-naros$NAROS_VERSION",
  "debian": { "suite": "$NAROS_SUITE", "snapshot": "$NAROS_SNAPSHOT" },
  "nash": $nash_ver,
  "toolchains": {},
  "caches": {}
}
EOF

echo "narOS identity: $(. "$R/etc/os-release" && echo "$PRETTY_NAME [$VARIANT/$NAROS_ARCH]")"
