#!/usr/bin/env bash
# job_lp2.sh: boots with /cache OFF the root disk (tmpfs /dev/shm), root guard at 84.5%.
#  c5/b5: logprobs requested on every request, census on: c = logprobs follow-up tree, b = #5204 tree (warm copy of the shared cache).
#  a5: ONE cold-cache boot of main (empty cache dir) for the clocks during the route + split race (host 250 ms logger).
cd ~/headroute; exec 9>/run/lock/arbi-gpu-0.lock; flock -w 43200 9 || exit 1
guard() { while sleep 10; do u=$(df -k --output=used,size / | tail -1 | awk "{printf \"%d\", 1000*\$1/\$2}"); [ "$u" -ge 845 ] && { echo "ROOT GUARD $u: stopping $(docker ps --format "{{.Names}}" | grep "^hr-[abc]5")"; docker ps --format "{{.Names}}" | grep "^hr-[abc]5" | xargs -r docker stop -t 30; }; done; }
guard & G=$!
export HR_CACHE=/dev/shm/headroute-warm; mkdir -p $HR_CACHE; rsync -a --exclude flat-weights --exclude s3c cache/ $HR_CACHE/
for t in ${LP_TAGS:-c5 b5}; do
  scripts/hr_boot2.sh ${t:0:1} $t census 2>&1 | cut -c1-200 || { echo "$t BOOT FAILED"; continue; }
  python3 scripts/lp_drive.py out/$t/drive > out/$t/drive.log 2>&1; echo "$t drive done $(date +%T) errs=$(grep -c "\"err\": \"" out/$t/drive.log)"
  scripts/hr_stop2.sh $t; grep "STOCK exl3_gemm launched" out/$t/engine.log | sed "s/^[0-9:]* [A-Z]* *//" | cut -c1-110 | sort | uniq -c
done
rm -rf /dev/shm/headroute-warm
if [ "${COLD:-1}" = 1 ]; then export HR_CACHE=/dev/shm/headroute-cold; rm -rf $HR_CACHE; mkdir -p $HR_CACHE
  echo "cold boot start $(date -u +%T)"; scripts/hr_boot2.sh a a5 2>&1 | cut -c1-200; echo "cold boot ready $(date -u +%T)"
  python3 scripts/lp_drive.py out/a5/drive > out/a5/drive.log 2>&1; echo "a5 steady drive done $(date -u +%T)"
  scripts/hr_stop2.sh a5; rm -rf /dev/shm/headroute-cold; fi
kill $G; echo "JOB_LP2_DONE root $(df --output=pcent / | tail -1)"; flock -u 9; exec 9>&-
