#!/bin/bash
# Strata bench, lane strata-stage-new: build the Strata engine at 6f32ec07 (v0.1.39) from source (never setup.py,
# never a release binary). The cmake lines are build-strata.sh's, byte for byte in their flags (CUDA sm_120,
# CUDA 13.4, tests off, ggml from the local llama.cpp 3cf03257 checkout via -DSTRATA_GGML_DIR so FetchContent never
# runs). Added for this build only, none of which changes a flag:
#  - the source pin is checked against the full sha AND against v0.1.39^{commit} first (STRATA-DELTA-2 C-9);
#  - cmake runs inside bwrap with no network (--unshare-net) and a read-only root: only the build folder, a fresh
#    HOME and a TMPDIR under the lane's heavy tree are writable, so a fetch or a write outside the build folder
#    fails loudly instead of happening;
#  - a clean environment (env -i) with PATH = CUDA 13.4's bin + /usr/bin:/bin.
# The SYCL, HIP gfx906, SM60 and ISA-floor options are left at their defaults (off / empty), as C-9 requires.
set -euo pipefail
SHORT=6f32ec07
FULL=6f32ec070f23ced9f50e704d854d775da52591ab
GG=/data/strata-bench/src/llama.cpp-3cf03257
SRC=/data/strata-bench/src/strata-$SHORT
OUT=/data/strata-bench/build/strata-$SHORT
LANE=/workshop/.cache/lanes/strata-stage-new
export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null
got=$(git -C "$SRC" --no-optional-locks rev-parse HEAD)
tag=$(git -C "$SRC" --no-optional-locks rev-parse 'v0.1.39^{commit}')
[ "$got" = "$FULL" ] || { echo "STOP: $SRC is at $got, want $FULL"; exit 3; }
[ "$tag" = "$FULL" ] || { echo "STOP: v0.1.39^{commit} is $tag, want $FULL"; exit 3; }
[ -z "$(git -C "$SRC" --no-optional-locks status --porcelain)" ] || { echo "STOP: $SRC has local changes"; exit 3; }
[ ! -e "$OUT" ] || { echo "STOP: $OUT already exists (launch once)"; exit 4; }
mkdir -p "$OUT" "$LANE/home" "$LANE/tmp"
SANDBOX=(/usr/bin/bwrap --unshare-net --die-with-parent --ro-bind / / --dev /dev --proc /proc --tmpfs /run
         --bind "$OUT" "$OUT" --bind "$LANE/home" "$LANE/home" --bind "$LANE/tmp" "$LANE/tmp" --
         /usr/bin/env -i PATH=/usr/local/cuda-13.4/bin:/usr/bin:/bin HOME="$LANE/home" TMPDIR="$LANE/tmp" LANG=C.UTF-8)
echo "$(date -u +%FT%TZ) BUILD START strata $FULL (v0.1.39^{commit} = $tag)"
"${SANDBOX[@]}" cmake -G Ninja -S "$SRC" -B "$OUT" -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \
  -DCMAKE_CUDA_ARCHITECTURES=120 -DCMAKE_CUDA_COMPILER=/usr/local/cuda-13.4/bin/nvcc -DSTRATA_GGML_DIR="$GG"
"${SANDBOX[@]}" cmake --build "$OUT" --target strata -j 8
echo "$(date -u +%FT%TZ) BUILD DONE strata $SHORT bin_sha=$(sha256sum "$OUT/strata" | cut -c1-16)"
