#!/usr/bin/env bash
# Run a batch of placement probes in ONE server-down window.
# Trials come from stdin, one per line; each line holds space-separated
# -ot overrides (empty line = baseline, no overrides).
#
# Usage:
#   printf '%s\n' "" '^blk\.43\.\w[\w.]*$=ROCm0' \
#     '^blk\.43\.\w[\w.]*$=ROCm0 ^blk\.41\.ffn_(gate|up|down)\.weight$=ROCm0' \
#   | run_trials.sh --history data/history_X.jsonl ~/run/launcher.sh
#
# Exits 3 if a production llama-server is running (start trials after stopping it).
set -euo pipefail
SKILL_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
HISTORY="$SKILL_DIR/data/placement_history.jsonl"
LAUNCHER=""
while [ $# -gt 0 ]; do
  case "$1" in
    --history) HISTORY="$2"; shift 2 ;;
    -*) echo "unknown option: $1" >&2; exit 2 ;;
    *) LAUNCHER="$1"; shift ;;
  esac
done
[ -n "$LAUNCHER" ] && [ -f "$LAUNCHER" ] || { echo "usage: run_trials.sh [--history F] <launcher>" >&2; exit 2; }

if pgrep -x llama-server >/dev/null 2>&1; then
  echo "error: production llama-server is running; stop it first (killall llama-server)" >&2
  exit 3
fi

n=0
while IFS= read -r line || [ -n "$line" ]; do
  [ -z "${line// /}" ] && line=""
  n=$((n+1))
  echo "=== trial $n: ${line:-<baseline>} ==="
  rc=0
  # shellcheck disable=SC2086
  "$SKILL_DIR/scripts/run_probe.sh" --history "$HISTORY" "$LAUNCHER" $line || rc=$?
  [ $rc -eq 0 ] || echo "warning: trial $n exited $rc" >&2
done
echo "=== all trials done; history: $HISTORY ==="
