#!/usr/bin/env bash
# Write repo/vfuse201.yaml: the base overlay plus an empty read-only mount over ONLY the image bakes the
# overlay preflight proves stale (stale_bakes(), the census agent's s3c_stale.py), unioned over the arms'
# trees so every arm boots with the same mounts. Run on box 201 after the arms' builds are in the share.
set -uo pipefail
N=/mnt/k8scache/agent-snapshots/exl3-vision-fuse-20261112; IMG=local/arbi-serve:main-43d0876
ST=/mnt/k8scache/agent-snapshots/s3census-20261112/scripts/s3c_stale.py
mkdir -p $HOME/vfuse/empty; : > /tmp/vfuse-mask.txt
for ARM in A B NULL; do
  MASK=()
  for it in 1 2 3 4 5; do
    found=$(docker run --rm --runtime runc "${MASK[@]}" -v $N/tree$ARM/arbi_serve:/opt/venv/lib/python3.12/site-packages/arbi_serve:ro \
      -v $N/share:/ext-cache:ro -e ARBI_EXT_SHARE_DIR=/ext-cache -v $ST:/s/st.py:ro -e S3C_CAP=8,9 -e CUDA_VISIBLE_DEVICES= \
      --entrypoint /opt/venv/bin/python $IMG -I /s/st.py 2>/dev/null); [ -z "$found" ] && break
    for p in $found; do MASK+=(-v $HOME/vfuse/empty:$p:ro); echo "$p" >> /tmp/vfuse-mask.txt; done
  done
done
sort -u /tmp/vfuse-mask.txt > $N/logs/mask-list.txt
python3 - "$N" <<'EOF'
import sys
n = sys.argv[1]
base = [l for l in open(n + "/scripts/vfuse201.yaml").read().split("\n") if "vfuse/empty" not in l and "image's bakes" not in l and "trees are newer" not in l]
i = base.index("  arbi-console:")
add = ["      # Image bakes stale_bakes() proves stale for the arms' trees: masked so each arm takes its tree's build from /ext-cache."]
add += [f"      - /home/arbi-admin/vfuse/empty:{p.strip()}:ro" for p in open(n + "/logs/mask-list.txt") if p.strip()]
open(n + "/repo/vfuse201.yaml", "w").write("\n".join(base[:i] + add + base[i:]))
EOF
cat $N/logs/mask-list.txt
