#!/usr/bin/env bash
# buildlock - run a heavy command while holding one of N machine-wide slots (default 2).
# Works on Linux (flock) and macOS (no flock by default -> python3 fcntl.flock fallback, or atomic mkdir as last resort).
# Usage:   buildlock <command...>        e.g.  buildlock pnpm turbo test
# Env:     BUILDLOCK_SLOTS (default 2)   BUILDLOCK_DIR (default /tmp)   BUILDLOCK_VERBOSE=1 to print wait/acquire lines
# Shared by agy, Copilot and Codex runs: take it only around heavy build/test commands, never around a whole CLI run.
set -u
[ $# -ge 1 ] || { echo "usage: buildlock <command...>" >&2; exit 2; }
SLOTS=${BUILDLOCK_SLOTS:-2}; DIR=${BUILDLOCK_DIR:-/tmp}
export NODE_OPTIONS=${NODE_OPTIONS:---max-old-space-size=3072}
say() { [ "${BUILDLOCK_VERBOSE:-0}" = 1 ] && echo "buildlock: $*" >&2; return 0; }

if command -v flock >/dev/null 2>&1; then
  # Linux (util-linux flock). The fd stays open across exec, so the lock lives as long as the command runs.
  say "waiting for slot (flock)"
  while :; do
    i=1
    while [ "$i" -le "$SLOTS" ]; do
      exec 9>"$DIR/.buildslot$i" || { i=$((i+1)); continue; }
      if flock -n 9; then say "acquired slot $i"; exec "$@"; fi
      exec 9>&-
      i=$((i+1))
    done
    sleep 1
  done
elif command -v python3 >/dev/null 2>&1; then
  # macOS / BSD: python3 fcntl.flock, same semantics as flock. Lock is held across exec.
  say "waiting for slot (python3 fcntl)"
  exec python3 -c '
import fcntl, os, sys, time
slots, d, verbose = int(sys.argv[1]), sys.argv[2], sys.argv[3] == "1"
cmd = sys.argv[4:]
while True:
    for i in range(1, slots + 1):
        try:
            fd = os.open(os.path.join(d, ".buildslot%d" % i), os.O_CREAT | os.O_RDWR, 0o666)
        except OSError:
            continue
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            os.close(fd); continue
        os.set_inheritable(fd, True)   # keep the lock after exec
        if verbose: print("buildlock: acquired slot %d" % i, file=sys.stderr)
        os.execvp(cmd[0], cmd)
    time.sleep(1)
' "$SLOTS" "$DIR" "${BUILDLOCK_VERBOSE:-0}" "$@"
else
  # Last resort: atomic mkdir slots (stale locks from killed jobs are cleared when the owner pid is gone).
  say "waiting for slot (mkdir)"
  while :; do
    i=1
    while [ "$i" -le "$SLOTS" ]; do
      L="$DIR/.buildslot$i.d"
      if mkdir "$L" 2>/dev/null; then echo $$ > "$L/pid"; break 2; fi
      op=$(cat "$L/pid" 2>/dev/null || true)
      if [ -n "$op" ] && ! kill -0 "$op" 2>/dev/null; then rm -rf "$L"; fi
      i=$((i+1))
    done
    sleep 1
  done
  trap 'rm -rf "$L"' EXIT INT TERM HUP
  say "acquired slot $i"
  "$@"; rc=$?
  exit $rc
fi
