#!/usr/bin/env bash
# Build the narOS kernel identity shim into os/dist/bin/libnaros-uname-<arch>.so
# (NAROS.md §2.3), the artifact os/packages/naros-identity/stage.sh packages.
#
#   build.sh [arch]        arch: arm64|amd64 (default: this host's)
#
# glibc, dynamically linked, on purpose: the shim only ever loads into glibc processes
# via /etc/ld.so.preload, and a static or musl build could not interpose them. CI builds
# arm64 with the gcc-aarch64-linux-gnu cross toolchain rather than zig (which the musl
# static binaries in this tree use) because a glibc shared object is exactly what the
# stock cross-gcc is for.
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OS_DIR="$(cd "$here/../.." && pwd)"
VERSION="$(cat "$OS_DIR/VERSION")"

case "${1:-$(dpkg --print-architecture 2>/dev/null || uname -m)}" in
    arm64 | aarch64) arch=arm64 ;;
    amd64 | x86_64) arch=amd64 ;;
    *) echo "unsupported arch: ${1:-}" >&2; exit 2 ;;
esac

# Cross only when the target differs from the host; a native build wants plain cc.
host="$(uname -m)"
cc=cc
if [ "$arch" = arm64 ] && [ "$host" != aarch64 ]; then cc=aarch64-linux-gnu-gcc; fi
if [ "$arch" = amd64 ] && [ "$host" != x86_64 ]; then cc=x86_64-linux-gnu-gcc; fi
command -v "$cc" > /dev/null || { echo "compiler not found: $cc" >&2; exit 2; }

out="$OS_DIR/dist/bin/libnaros-uname-$arch.so"
mkdir -p "$(dirname "$out")"
"$cc" -shared -fPIC -O2 -Wall -Wextra \
    -DNAROS_KERNEL_TAG="\"-naros$VERSION\"" \
    -o "$out" "$here/uname.c"
# Match strip to the compiler: the host's strip cannot touch a cross-built object.
strip_bin=strip
[ "$cc" = cc ] || strip_bin="${cc%gcc}strip"
"$strip_bin" "$out" 2> /dev/null || true

echo "built $out (tag -naros$VERSION, $cc)"
