#!/usr/bin/env bash
# lock_take.sh <card-UUID> -- TAKE the card lock for the Von and Laya speed leg (DV-5), only when the card is free
# and empty. The house's take script (bench/ollama-vs-vllm-2026-09-28/dtt/tools/ovv_dtt_lock_take.sh) with the
# lock word `dv-speed`, and one change for the pen: the compute-process query asks for pid and memory only, never
# the card's UUID, so no UUID is ever printed.
#
# What this file is, for a reader who opened it cold. The bench box's one RTX 3090 is shared by several bench lanes in
# turn; the lane that holds /workshop/CARD-LOCK owns the card (D-20260928-024/-025). This script, run on the bench box, takes the
# lock for `dv-speed` only when (1) no lock file exists, and (2) the card, read by its UUID on the host, shows 1 MiB
# used, a 300.00 W limit, persistence Enabled, and no compute process. It prints its reading either way. The lock is
# written with noclobber, so two lanes racing for it cannot both win. It never touches the card.
#
# Exit: 0 the lock is ours (its line printed) · 4 busy or not empty (the reason printed) · 2 usage.
set -u
UUID="${1:?usage: lock_take.sh <card-UUID>}"
LOCK="$HOME/CARD-LOCK"
now="$(date -u +%FT%TZ)"
if [ -e "$LOCK" ]; then
  echo "$now BUSY: $LOCK reads '$(head -n 1 "$LOCK")'"
  exit 4
fi
row="$(nvidia-smi --id="$UUID" --query-gpu=memory.used,power.limit,persistence_mode --format=csv,noheader,nounits 2>&1)"
apps="$(nvidia-smi --id="$UUID" --query-compute-apps=pid,used_memory --format=csv,noheader 2>&1)"
echo "$now card: $row | compute apps: ${apps:-none}"
IFS=',' read -r used cap pm <<< "$row"
used="${used// /}"; cap="${cap// /}"; pm="${pm// /}"
if [ "$used" != "1" ] || [ "$cap" != "300.00" ] || [ "$pm" != "Enabled" ] || [ -n "$apps" ]; then
  echo "$now NOT EMPTY AT ITS POSTURE: the lock is not taken"
  exit 4
fi
set -o noclobber
if ! { echo "dv-speed $now" > "$LOCK"; } 2>/dev/null; then
  echo "$now BUSY: another lane wrote $LOCK first: '$(head -n 1 "$LOCK")'"
  exit 4
fi
echo "$now LOCK TAKEN: $(head -n 1 "$LOCK")"
exit 0
