#!/usr/bin/env bash
# Build the Nucleic Linux guest agent as a self-contained arm64 binary.
#
# Prefers a fully static link (so the one binary runs on any arm64 Linux guest regardless of its libc),
# and falls back to a normal dynamic link when a static libc isn't installed in the build environment.
# Run inside the Nucleic Linux build container (arm64), where `cc` targets the guest architecture.
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
src="$here/src/agent.c"
outdir="${1:-$here/build}"
out="$outdir/nucleic-linux-agent"
mkdir -p "$outdir"

cflags=(-O2 -Wall -Wextra -pthread)

if cc "${cflags[@]}" -static -o "$out" "$src" 2>/dev/null; then
    link="static"
else
    echo "static link unavailable — falling back to dynamic" >&2
    cc "${cflags[@]}" -o "$out" "$src"
    link="dynamic"
fi

strip "$out" 2>/dev/null || true
echo "built $out ($link, $(uname -m))"
file "$out" 2>/dev/null || true
