#!/bin/bash
# render_slot.sh: run a headless-Chrome render while holding one of N shared render slots,
# so the page agents together never run more than N Chromes on the Mac at once.
# Usage: bash _tools/render_slot.sh <command> [args...]
# The slot count comes from RENDER_SLOTS (default 2). A slot whose holder PID is gone is reclaimed.
# The command runs under nice -n 20.
N="${RENDER_SLOTS:-2}"
BASE="/Volumes/Workspace/Scratch/coord/render_slots"
mkdir -p "$BASE"
slot=""
# A perf lab can pause all page renders for a clean measurement by writing its PID into $BASE/PAUSE.
# Renders wait while that PID is alive; a PAUSE whose holder is gone is removed.
PAUSE="$BASE/PAUSE"
while [ -f "$PAUSE" ]; do
  pp=$(cat "$PAUSE" 2>/dev/null)
  if [ -n "$pp" ] && kill -0 "$pp" 2>/dev/null; then sleep 5; else rm -f "$PAUSE"; fi
done
while [ -z "$slot" ]; do
  for i in $(seq 1 "$N"); do
    d="$BASE/slot.$i"
    if mkdir "$d" 2>/dev/null; then
      echo $$ > "$d/pid"; slot="$d"; break
    fi
    p=$(cat "$d/pid" 2>/dev/null)
    if [ -n "$p" ] && ! kill -0 "$p" 2>/dev/null; then
      python3 -c "import shutil,sys; shutil.rmtree(sys.argv[1], ignore_errors=True)" "$d"
    fi
  done
  [ -z "$slot" ] && sleep 2
done
trap 'python3 -c "import shutil,sys; shutil.rmtree(sys.argv[1], ignore_errors=True)" "$slot"' EXIT INT TERM
nice -n 20 "$@"
