#!/usr/bin/env bash
# Runs a lab-only test inside the dangerlab guest — the ONLY sanctioned way to execute
# the exhaustion-class tests in this directory.
#
# usage: run-in-lab.sh <test-file-name> [timeout-seconds]
#
# dangerlab lives on debian1 and dangerlab-run's --payload is a path ON debian1, so this
# ships this module there first. debian1 is reached with an explicit option set built from
# ~/.ssh/config: a plain `ssh debian1` aborts under the agent sandbox, whose view of
# /etc/ssh/ssh_config.d is owned by nobody ("Bad owner or permissions").
set -uo pipefail

TESTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE="$(cd "$TESTS/.." && pwd)"
TEST="${1:?usage: run-in-lab.sh <test-file-name> [timeout-seconds]}"
TIMEOUT="${2:-300}"
TEST="$(basename -- "$TEST")"
[[ -f "$TESTS/$TEST" ]] || { printf 'run-in-lab: no such test: %s/%s\n' "$TESTS" "$TEST" >&2; exit 2; }

ssh_field() {
  awk -v want="$1" '
    /^[Hh]ost[ \t]/ { inblock = ($2 == "debian1"); next }
    inblock && tolower($1) == tolower(want) { print $2; exit }
  ' "$HOME/.ssh/config"
}
HOST_NAME="$(ssh_field HostName)"; PORT="$(ssh_field Port)"
LOGIN="$(ssh_field User)"; KEY="$(ssh_field IdentityFile)"
KEY="${KEY/#\~/$HOME}"
for f in HOST_NAME PORT LOGIN KEY; do
  [[ -n "${!f}" ]] || { printf 'run-in-lab: ~/.ssh/config has no %s for host debian1\n' "$f" >&2; exit 3; }
done

SSH=(ssh -F /dev/null -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new
     -o UserKnownHostsFile="$HOME/.ssh/known_hosts" -i "$KEY" -p "$PORT")
# Per-invocation staging: the lab runs N agents' tests concurrently, and one shared
# payload path with `rsync --delete` meant whoever synced last overwrote the tree the
# others were about to run.
STAGE="$("${SSH[@]}" "$LOGIN@$HOST_NAME" 'mktemp -d /tmp/dangerlab-payload.XXXXXXXX')" || {
  printf 'run-in-lab: cannot reach debian1\n' >&2; exit 4; }
REMOTE_PAYLOAD="$STAGE/claude"

printf 'run-in-lab: shipping %s -> debian1:%s\n' "$MODULE" "$REMOTE_PAYLOAD" >&2
"${SSH[@]}" "$LOGIN@$HOST_NAME" "mkdir -p '$REMOTE_PAYLOAD'" || {
  printf 'run-in-lab: cannot create the staging dir\n' >&2; exit 4; }
rsync -a --delete --exclude .git -e "${SSH[*]}" "$MODULE/" "$LOGIN@$HOST_NAME:$REMOTE_PAYLOAD/" || {
  "${SSH[@]}" "$LOGIN@$HOST_NAME" "rm -rf '$STAGE'"
  printf 'run-in-lab: payload sync failed\n' >&2; exit 5; }

"${SSH[@]}" "$LOGIN@$HOST_NAME" \
  "/home/user/dangerlab/dangerlab-run --payload '$REMOTE_PAYLOAD' --timeout '$TIMEOUT' -- bash claude/tests/$TEST"
RC=$?
"${SSH[@]}" "$LOGIN@$HOST_NAME" "rm -rf '$STAGE'"
exit "$RC"
