#!/usr/bin/env bash
# GPU-free build of one arm's int8 served set + a_prep for sm_89, published to the snapshot's ext share.
# usage: build_arm.sh ARM   (takes the build lock; jobs sized from MemAvailable)
set -uo pipefail
ARM=$1
N=/mnt/k8scache/agent-snapshots/exl3-vision-fuse-20261112
IMG=registry.arbi.work/arbi-serve@sha256:4eeaad6fb2fcd66a2a24c90cdb89af4c6db533a0f9b661ceaaa4e5a1abcd1725
exec 9</run/lock/arbi-build.lock; flock 9
AVAIL=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo)
JOBS=$(( (AVAIL - 6) / 6 )); [ $JOBS -gt 2 ] && JOBS=2
[ $JOBS -ge 1 ] || { echo "MemAvailable ${AVAIL}G: no room for one unit"; exit 3; }
echo "arm $ARM avail=${AVAIL}G jobs=$JOBS $(date -Is)"
W=/tmp/vfuse-build-$ARM; rm -rf $W; mkdir -p $W/ext; chmod -R 777 $W
docker run --rm --name vfuse-build-$ARM --memory $((JOBS * 7))g --cpus $((JOBS * 4)) --user 0:0 \
  -v $N/tree$ARM/arbi_serve:/opt/venv/lib/python3.12/site-packages/arbi_serve:ro \
  -v /mnt/k8scache/models:/models:ro -v $N/share:/ext-share -v $W/ext:/ext -v $N/scripts:/s:ro \
  -e TORCH_CUDA_ARCH_LIST=${ARCH:-8.9} -e I8_MAX_JOBS=$JOBS -e MAX_JOBS=$JOBS -e ARBI_EXT_SHARE_DIR=/ext-share \
  -e TORCH_EXTENSIONS_DIR=/ext -e PYTHONDONTWRITEBYTECODE=1 -e CUDA_VISIBLE_DEVICES= \
  --entrypoint python $IMG -I /s/build_arm.py
rc=$?; docker run --rm --runtime runc --user 0:0 -v $W:/w --entrypoint rm $IMG -rf /w/ext; rm -rf $W; echo "arm $ARM rc=$rc $(date -Is)"; exit $rc
