#!/usr/bin/env bash
#
# Build nash (shell/nash — docs/NASH.md) as an arm64 macOS binary: the one darwin artifact
# that M5 (macOS-VM provisioning stages it → guest /usr/local/bin/nash, NASH.md §7.5) and
# M5.5 (the in-app-bundle host copy, §7.7/§8) both consume. Linux slices are built elsewhere
# (naros.yml, static musl); this script is the darwin counterpart, run on the HOST or CI —
# never in the guest.
#
#   ./scripts/build-nash-macos.sh [output-dir]     # default output: shell/dist/macos
#
# Produces <output-dir>/nash (arm64 only — no x86_64 slice, no lipo). Both consumers floor at
# macOS 27 (Package.swift; the MACOS_VM_NATIVE_AGENT.md guest pin), and macOS 26 was Apple's last
# Intel release, so no x86_64 host or guest can ever run this binary. Needs cargo with the
# aarch64-apple-darwin std target; when rustup is present it is added automatically.

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORKSPACE="$REPO_ROOT/shell"
OUT_DIR="${1:-$WORKSPACE/dist/macos}"

# Keep cargo's target dir off virtiofs when building from a macOS-VM share — same rationale as
# scripts/lib/build-scratch.sh for SwiftPM; cargo takes the redirect via CARGO_TARGET_DIR. An
# explicit CARGO_TARGET_DIR from the caller always wins.
if [ -z "${CARGO_TARGET_DIR:-}" ]; then
  SCRATCH_ARGS="$(bash "$REPO_ROOT/scripts/lib/build-scratch.sh" "$WORKSPACE")"
  if [ -n "$SCRATCH_ARGS" ]; then
    export CARGO_TARGET_DIR="${SCRATCH_ARGS#--scratch-path }/cargo-target"
  fi
fi
TARGET_DIR="${CARGO_TARGET_DIR:-$WORKSPACE/target}"

TARGET=aarch64-apple-darwin

if command -v rustup >/dev/null 2>&1; then
  rustup target add "$TARGET" >/dev/null 2>&1 || true
fi
echo "▸ Building nash ($TARGET, release) …"
(cd "$WORKSPACE" && cargo build --release --target "$TARGET" -p nash)

mkdir -p "$OUT_DIR"
cp "$TARGET_DIR/$TARGET/release/nash" "$OUT_DIR/nash"
chmod 0755 "$OUT_DIR/nash"

echo "  slices: $(lipo -archs "$OUT_DIR/nash")"
echo "  version: $("$OUT_DIR/nash" --version)"
echo "✓ $OUT_DIR/nash"
echo "  Stage it for provisioning (next to provision-macos-guest.sh in the guest share) or let"
echo "  scripts/package-app.sh embed it at Resources/macvm/nash."
