#!/usr/bin/env bash
# lock_release.sh <card-UUID> -- RELEASE the card lock after the Von and Laya speed leg (DV-5), only when the card is
# empty at its posture. The house's release script (bench/ollama-vs-vllm-2026-09-28/dtt/tools/ovv_dtt_lock_release.sh)
# with the lock word `dv-speed`, this leg's unit names (`dv-speed-*`), and the compute-process query without the UUID.
#
# What this file is, for a reader who opened it cold. The lane that holds /workshop/CARD-LOCK owns the bench box's RTX 3090
# (D-20260928-024/-025). This script, run on the bench box, removes the lock only when (1) it names `dv-speed` (never
# another lane's lock), (2) no `dv-speed-*` unit is still active, and (3) 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
# and never touches the card.
#
# Exit: 0 released (the reading printed) · 4 not released (the reason printed) · 2 usage.
set -u
UUID="${1:?usage: lock_release.sh <card-UUID>}"
LOCK="$HOME/CARD-LOCK"
now="$(date -u +%FT%TZ)"
first="$(awk 'NR == 1 { print $1; exit }' "$LOCK" 2>/dev/null)"
if [ "$first" != "dv-speed" ]; then
  echo "$now NOT OURS: $LOCK reads '$(head -n 1 "$LOCK" 2>/dev/null)'; nothing removed"
  exit 4
fi
units="$(systemctl --user list-units --state=active,activating,deactivating --no-legend --plain 'dv-speed-*' 2>&1)"
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} | dv-speed units: ${units:-none}"
IFS=',' read -r used cap pm <<< "$row"
used="${used// /}"; cap="${cap// /}"; pm="${pm// /}"
if [ -n "$units" ] || [ "$used" != "1" ] || [ "$cap" != "300.00" ] || [ "$pm" != "Enabled" ] || [ -n "$apps" ]; then
  echo "$now NOT EMPTY AT ITS POSTURE: the lock stays"
  exit 4
fi
rm -f "$LOCK"
echo "$now LOCK RELEASED"
exit 0
