#!/bin/zsh
set -eu
[[ ${TART_XCUI_TRACE:-0} == 1 ]] && set -x

SCRIPT=${0:A}
REFERENCES=${SCRIPT:h}
ROOT=${REFERENCES:h:h:h}
# Marketplaces install this plugin by git clone, so "$ROOT/.git" exists in a
# plugin cache too and cannot by itself distinguish a source checkout. Without
# the extra guards every install gets its own DATA_HOME: Claude Code and Codex
# each build a separate golden image, and because the cache path is version
# pinned, every plugin update orphans the previous image and rebuilds from
# scratch.
if [[ -d "$ROOT/.git" && -z ${CLAUDE_PLUGIN_ROOT:-}${CODEX_PLUGIN_ROOT:-} && "$ROOT" != */plugins/cache/* ]]; then
  DEFAULT_DATA_HOME=$ROOT
else
  DEFAULT_DATA_HOME="$HOME/Library/Application Support/Tart Xcode Runner"
fi
DATA_HOME=${TART_XCUI_DATA_HOME:-$DEFAULT_DATA_HOME}
export TART_HOME=${TART_XCUI_TART_HOME:-"$DATA_HOME/.tart"}

BASE_VM=${TART_XCUI_BASE_VM:-tart-xcui-base}
CANDIDATE_VM=${TART_XCUI_CANDIDATE_VM:-${BASE_VM}-candidate}
PREVIOUS_VM=${TART_XCUI_PREVIOUS_VM:-${BASE_VM}-previous}
IMAGE=${TART_XCUI_IMAGE:-ghcr.io/cirruslabs/macos-tahoe-xcode@sha256:61f6e857a3d65dd2f8daf9c51c7b837fa458bcc9181ae8556e645b534dab6bf6}
CPU=${TART_XCUI_CPU:-8}
MEMORY=${TART_XCUI_MEMORY:-24576}
DISK_SIZE=${TART_XCUI_DISK_SIZE:-150}
READY_TIMEOUT=${TART_XCUI_READY_TIMEOUT:-300}
RUN_TIMEOUT=${TART_XCUI_RUN_TIMEOUT:-7200}
GUEST_PASSWORD=${TART_XCUI_GUEST_PASSWORD:-admin}
RESULTS=${TART_XCUI_RESULTS:-"$DATA_HOME/results"}
STATE="$DATA_HOME/.state"
RUNS_DIR="$STATE/runs"
LOCK="$STATE/runner.lock"
HOST_CRASH_QUARANTINE="$STATE/host-crash-quarantine"
DIAGNOSTIC_REPORTS=${TART_XCUI_DIAGNOSTIC_REPORTS:-/Library/Logs/DiagnosticReports}
MAX_REPO_FILES=${TART_XCUI_MAX_REPO_FILES:-100000}
WORK_VM=
RUN_ID=
RUN_RESULT_DIR=
RUN_TART_LOG=
RUN_BOOT_DIR=
RUN_EXIT_CODE=1

zmodload zsh/system
integer LOCK_FD

usage() {
  cat <<'EOF'
Usage:
  tart-runner doctor
  tart-runner prepare [--replace] [OCI_OR_LOCAL_IMAGE]
  tart-runner add-platform PLATFORM...
  tart-runner add-component MetalToolchain
  tart-runner run [--repo PATH] -- COMMAND...
  tart-runner build --repo PATH -- XCODEBUILD_ARGS...
  tart-runner xcui-test --repo PATH -- XCODEBUILD_ARGS...
  tart-runner smoke
  tart-runner reset [--acknowledge-host-crash]
  tart-runner clean [--results DAYS] [--images]
  tart-runner rollback

Runs may execute in parallel; each uses its own disposable clone. Image
operations (prepare, add-*, reset, rollback) are exclusive and refuse to
start while runs are active.

Environment:
  TART_XCUI_DATA_HOME, TART_XCUI_TART_HOME, TART_XCUI_BASE_VM (select a
  golden image; candidate/previous/work VM names derive from it),
  TART_XCUI_IMAGE, TART_XCUI_CPU, TART_XCUI_MEMORY, TART_XCUI_DISK_SIZE,
  TART_XCUI_RUN_TIMEOUT, TART_XCUI_RESULTS, TART_XCUI_KEEP_FAILED=1,
  TART_XCUI_MAX_REPO_FILES (100000)
EOF
}

die() {
  print -u2 -- "error: $*"
  exit 1
}

prepare_dirs() {
  mkdir -p "$TART_HOME" "$RESULTS" "$STATE" "$RUNS_DIR" "$STATE/boots"
}

tart_from() {
  local directory=$1
  shift
  (cd "$directory" && tart "$@")
}

fresh_boot_dir() {
  local directory="$STATE/boots/$1"
  [[ $directory == "$STATE/boots/"* ]] || die "refusing unsafe boot directory: $directory"
  # A leftover control socket here is not automatically garbage. Blindly
  # rm -rf'ing the directory would delete a socket a LIVE tart still owns,
  # turning someone else's running VM into an unexplained failure. Distinguish
  # the two cases before touching anything (issue #5).
  if [[ -d $directory ]]; then
    local -a entries owners
    # find, not a glob qualifier: bare glob qualifiers are disabled in some
    # shell configurations (NO_BARE_GLOB_QUAL), and a silently-empty match here
    # would read as "nothing owns it" — the exact wrong answer.
    local find_status=0
    entries=(${(f)"$(find "$directory" -mindepth 1 -maxdepth 1 2>/dev/null)"}) || find_status=$?
    # Fail closed: an inspection error must not read as "nothing owns it".
    (( find_status == 0 )) ||
      die "cannot inspect boot directory $directory (find exited $find_status); refusing to treat it as stale"
    owners=()
    if (( ${#entries} > 0 )); then
      local -a raw_owners
      local lsof_status=0 lsof_err
      # lsof returns exit 1 for "no owner found" AND for errors like a permission
      # failure inspecting a path. The error text tells them apart:
      # "no file use located:" is the benign failed search, but anything else
      # (status/permission errors) means lsof could not answer the ownership
      # question and the directory must fail closed, not quarantine.
      lsof_err="$(lsof -V -t -- "${entries[@]}" 2>&1 >/dev/null)" || lsof_status=$?
      local owners_status=0
      raw_owners=(${(f)"$(lsof -t -- "${entries[@]}" 2>/dev/null)"}) || owners_status=$?
      local benign='no file use located:'
      (( lsof_status == 0 || lsof_status == 1 )) ||
        die "cannot inspect boot directory $directory (lsof -V exited $lsof_status); refusing to treat it as stale"
      (( owners_status == 0 || owners_status == 1 )) ||
        die "cannot inspect boot directory $directory (lsof exited $owners_status); refusing to treat it as stale"
      if print -r -- $lsof_err | grep -v -- "$benign" | grep -q .; then
        die "cannot verify owners of boot directory $directory; lsof could not answer ownership for every entry:" '$'\n'' "$lsof_err"
      fi
      owners=(${(u)raw_owners})
    fi
    if (( ${#owners} > 0 )); then
      die "refusing to reuse boot directory $directory: still owned by live pid(s) ${owners[*]}. Stop that run, or wait for it to finish."
    fi
    # Unowned: an interrupted run left it. Quarantine rather than delete, so the
    # evidence survives for the same reason interrupted runs keep their markers.
    local stamp quarantine
    stamp=$(date +%Y%m%d-%H%M%S)
    quarantine="$STATE/quarantine/boots/$1-$stamp"
    mkdir -p -- "${quarantine:h}"
    mv -- "$directory" "$quarantine" ||
      die "could not quarantine stale boot directory $directory"
    print -u2 -- "tart: quarantined stale boot directory from an interrupted run -> $quarantine"
  fi
  mkdir -p "$directory"
  print -r -- "$directory"
}

remove_boot_dir() {
  local directory=$1
  [[ -z $directory ]] && return 0
  [[ $directory == "$STATE/boots/"* ]] || die "refusing unsafe boot directory cleanup: $directory"
  rm -rf -- "$directory"
}

lock_runner() {
  local timeout=${1:-300}
  : >>"$LOCK"
  zsystem flock -t "$timeout" -f LOCK_FD "$LOCK" ||
    die "another runner operation holds the lock; retry shortly"
}

unlock_runner() {
  zsystem flock -u "$LOCK_FD" 2>/dev/null || true
}

# Runs register a pidfile while their VM is alive. Image operations must not
# mutate or boot the golden image while any run's clone might depend on it.
# With a wait budget, drains: the caller holds the runner lock, so no new
# runs can start while we wait for the active ones to finish.
ensure_no_active_runs() {
  local timeout=${1:-0} f pid active
  local deadline=$((SECONDS + timeout))
  while true; do
    active=
    for f in "$RUNS_DIR"/*.pid(N); do
      pid=$(<"$f")
      if kill -0 "$pid" 2>/dev/null; then
        active=$pid
      else
        rm -f "$f"
      fi
    done
    [[ -n $active ]] || return 0
    (( SECONDS < deadline )) ||
      die "a run (pid $active) is active; retry after it finishes"
    sleep 15
  done
}

need_tart() {
  command -v tart >/dev/null ||
    die "Tart is missing; run: brew tap openai/tools && brew trust --tap openai/tools && brew install openai/tools/tart"
}

runner_pid_is_active() {
  local marker=$1 pid command
  pid=$(sed -n '1{s/[^0-9].*$//;p;}' "$marker" 2>/dev/null || true)
  [[ $pid == <-> ]] || return 1
  kill -0 "$pid" 2>/dev/null || return 1
  command=$(ps -p "$pid" -o command= 2>/dev/null || true)
  [[ $command == *"$SCRIPT"* ]]
}

host_failure_after_marker() {
  local marker=$1 candidate
  local -a roots
  roots=()
  [[ -d $DIAGNOSTIC_REPORTS ]] && roots+=("$DIAGNOSTIC_REPORTS")
  [[ -d "$DIAGNOSTIC_REPORTS/Retired" ]] && roots+=("$DIAGNOSTIC_REPORTS/Retired")
  for candidate in ${^roots}/*.panic(N); do
    [[ $candidate -nt $marker ]] || continue
    grep -q '^panic(' "$candidate" 2>/dev/null || continue
    print -r -- "$candidate"
    return 0
  done
  for candidate in ${^roots}/*.ips(N); do
    [[ $candidate -nt $marker ]] || continue
    # A system-wide file-table failure can terminate loginwindow/WindowServer
    # without producing a kernel panic. Treat that graphical-session crash as
    # equally unsafe: it logs the same resource error seen in the guest copy.
    grep -Fq 'Too many open files in system' "$candidate" 2>/dev/null || continue
    grep -Eq '"app_name":"(loginwindow|WindowServer)"' "$candidate" 2>/dev/null || continue
    print -r -- "$candidate"
    return 0
  done
}

record_interrupted_run_state() {
  local marker diagnostic run_id
  for marker in "$RUNS_DIR"/*.pid(N); do
    runner_pid_is_active "$marker" && continue
    diagnostic=$(host_failure_after_marker "$marker")
    [[ -n $diagnostic ]] || continue
    run_id=${marker:t:r}
    if [[ ! -f $HOST_CRASH_QUARANTINE ]]; then
      {
        print "run=$run_id"
        print "diagnostic=${diagnostic:t}"
        print "detected=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
      } >"$HOST_CRASH_QUARANTINE"
    fi
  done
}

refuse_unsafe_state() {
  local marker
  record_interrupted_run_state
  if [[ -f $HOST_CRASH_QUARANTINE ]]; then
    die "host crash quarantine is active; inspect the recorded diagnostic and run 'tart-runner reset --acknowledge-host-crash' only after the host risk is understood"
  fi
  for marker in "$RUNS_DIR"/*.pid(N); do
    runner_pid_is_active "$marker" && continue
    die "an earlier run ended without cleanup (${marker:t:r}); inspect its result and run 'tart-runner reset' before starting another VM"
  done
}

preflight_repo() {
  local repo=$1 overflow
  [[ $MAX_REPO_FILES == <-> ]] && (( MAX_REPO_FILES > 0 )) ||
    die "TART_XCUI_MAX_REPO_FILES must be a positive integer"
  overflow=$(find "$repo" \
    -type d \( -name .git -o -name .build -o -name 'DerivedData*' -o -name results \) -prune -o \
    \( -type f -o -type l \) -print 2>/dev/null |
    sed -n "$(( MAX_REPO_FILES + 1 )){p;q;}")
  [[ -z $overflow ]] ||
    die "repository payload exceeds the safe file limit ($MAX_REPO_FILES); remove or relocate generated outputs before starting a VM"
}

vm_exists() {
  tart list --source local -q | grep -Fqx -- "$1"
}

stop_vm() {
  local vm=$1
  vm_exists "$vm" || return 0
  tart stop "$vm" --timeout 30 >/dev/null 2>&1 || true
}

delete_vm() {
  local vm=$1
  vm_exists "$vm" || return 0
  tart delete "$vm"
}

wait_for_agent() {
  local vm=$1 run_pid=${2:-} boot_dir=${3:-$PWD}
  local deadline=$((SECONDS + READY_TIMEOUT))

  until tart_from "$boot_dir" exec "$vm" /usr/bin/true >/dev/null 2>&1; do
    [[ -z $run_pid ]] || kill -0 "$run_pid" 2>/dev/null || return 1
    (( SECONDS < deadline )) || return 1
    sleep 2
  done
}

promote_candidate() {
  local candidate=$1
  stop_vm "$candidate"
  stop_vm "$BASE_VM"
  delete_vm "$PREVIOUS_VM"
  if vm_exists "$BASE_VM"; then
    tart clone "$BASE_VM" "$PREVIOUS_VM"
    delete_vm "$BASE_VM"
  fi
  if ! tart clone "$candidate" "$BASE_VM"; then
    vm_exists "$PREVIOUS_VM" && tart clone "$PREVIOUS_VM" "$BASE_VM"
    die "promotion failed; restored $BASE_VM from $PREVIOUS_VM"
  fi
}

doctor() {
  local failed=0
  prepare_dirs

  [[ $(uname -m) == arm64 ]] && print "host:       arm64" || {
    print "host:       unsupported ($(uname -m))"
    failed=1
  }
  command -v tart >/dev/null && print "tart:       $(tart --version)" || {
    print "tart:       missing"
    failed=1
  }
  print "TART_HOME:  $TART_HOME"
  df -h "$TART_HOME" | tail -1
  command -v tart >/dev/null && vm_exists "$BASE_VM" &&
    print "base VM:    $BASE_VM (ready)" || {
      print "base VM:    $BASE_VM (missing; run prepare)"
      failed=1
    }
  local f active=0 interrupted=0
  record_interrupted_run_state
  for f in "$RUNS_DIR"/*.pid(N); do
    if runner_pid_is_active "$f"; then
      (( ++active ))
    else
      (( ++interrupted ))
    fi
  done
  print "active runs: $active"
  print "interrupted runs: $interrupted"
  if [[ -f $HOST_CRASH_QUARANTINE ]]; then
    print "host safety: QUARANTINED (host failure followed an interrupted run)"
    failed=1
  elif (( interrupted )); then
    print "host safety: recovery required (run reset before another VM)"
    failed=1
  else
    print "host safety: ready"
  fi
  security show-keychain-info "$HOME/Library/Keychains/login.keychain-db" >/dev/null 2>&1 &&
    print "keychain:   login keychain available" ||
    print "keychain:   WARNING: unlock login.keychain before headless VM starts"
  return "$failed"
}

prepare_base() {
  local replace=0 image=$IMAGE run_pid boot_dir
  [[ ${1:-} == --replace ]] && {
    replace=1
    shift
  }
  [[ $# -le 1 ]] || die "prepare accepts at most one OCI or local image"
  [[ $# -eq 0 ]] || image=$1

  if vm_exists "$BASE_VM" && (( ! replace )); then
    print "Base VM already exists: $BASE_VM"
    return 0
  fi

  stop_vm "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  print "Cloning candidate from $image"
  tart clone "$image" "$CANDIDATE_VM"
  tart set "$CANDIDATE_VM" --cpu "$CPU" --memory "$MEMORY" --disk-size "$DISK_SIZE"
  boot_dir=$(fresh_boot_dir "prepare-$CANDIDATE_VM")
  trap 'stop_vm "$CANDIDATE_VM"' EXIT INT TERM HUP
  tart_from "$boot_dir" run --no-graphics "$CANDIDATE_VM" >"$STATE/prepare.log" 2>&1 &
  run_pid=$!
  print "Waiting for the guest agent..."
  wait_for_agent "$CANDIDATE_VM" "$run_pid" "$boot_dir" ||
    die "candidate failed to start; see $STATE/prepare.log"
  tart_from "$boot_dir" exec "$CANDIDATE_VM" /bin/zsh -lc '
    set -e
    /usr/bin/xcodebuild -version
    /usr/bin/xcodebuild -checkFirstLaunchStatus
    /usr/bin/xcrun -f clang >/dev/null
    /usr/bin/xcrun -f metal >/dev/null
    /usr/bin/xcrun simctl list runtimes available | /usr/bin/grep -q iOS
    test "$(/usr/bin/stat -f %Su /dev/console)" != root
    login_user=$(/usr/bin/defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser)
    test -n "$login_user"
    test "$login_user" != root
    test "$(/usr/bin/defaults -currentHost read com.apple.screensaver idleTime)" = 0
  '
  stop_vm "$CANDIDATE_VM"
  remove_boot_dir "$boot_dir"
  trap - EXIT INT TERM HUP

  promote_candidate "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  print "Ready: $BASE_VM"
}

add_xcode_items() {
  local kind=$1 run_pid item log_name boot_dir
  shift
  (( $# > 0 )) || die "add-$kind requires at least one value"
  vm_exists "$BASE_VM" || die "base VM is missing; run prepare"
  for item in "$@"; do
    if [[ $kind == platform ]]; then
      [[ $item == iOS || $item == tvOS || $item == watchOS || $item == visionOS ]] ||
        die "unsupported platform: $item"
    else
      [[ $item == MetalToolchain ]] || die "unsupported component: $item"
    fi
  done

  log_name="add-$kind.log"
  stop_vm "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  tart clone "$BASE_VM" "$CANDIDATE_VM"
  boot_dir=$(fresh_boot_dir "add-$kind-$CANDIDATE_VM")
  trap 'stop_vm "$CANDIDATE_VM"' EXIT INT TERM HUP
  tart_from "$boot_dir" run --no-graphics "$CANDIDATE_VM" >"$STATE/$log_name" 2>&1 &
  run_pid=$!
  wait_for_agent "$CANDIDATE_VM" "$run_pid" "$boot_dir" ||
    die "candidate failed to start; see $STATE/$log_name"
  for item in "$@"; do
    print "Installing $item..."
    if [[ $kind == platform ]]; then
      tart_from "$boot_dir" exec "$CANDIDATE_VM" /bin/zsh -c \
        'print -r -- "$1" | /usr/bin/sudo -S /usr/bin/xcodebuild -downloadPlatform "$2"' \
        -- "$GUEST_PASSWORD" "$item"
      tart_from "$boot_dir" exec "$CANDIDATE_VM" /bin/zsh -lc \
        "/usr/bin/xcrun simctl list runtimes available | /usr/bin/grep -Fq '$item'"
    else
      tart_from "$boot_dir" exec "$CANDIDATE_VM" /bin/zsh -c \
        'print -r -- "$1" | /usr/bin/sudo -S /usr/bin/xcodebuild -downloadComponent "$2"' \
        -- "$GUEST_PASSWORD" "$item"
      tart_from "$boot_dir" exec "$CANDIDATE_VM" /usr/bin/xcrun -f metal >/dev/null
    fi
  done
  stop_vm "$CANDIDATE_VM"
  remove_boot_dir "$boot_dir"
  trap - EXIT INT TERM HUP

  promote_candidate "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  print "Updated: $BASE_VM"
}

cleanup_work_vm() {
  stop_vm "$WORK_VM"
  [[ -n $RUN_RESULT_DIR && -f $RUN_TART_LOG ]] &&
    cp "$RUN_TART_LOG" "$RUN_RESULT_DIR/tart.log"
  if (( RUN_EXIT_CODE != 0 )) && [[ ${TART_XCUI_KEEP_FAILED:-0} == 1 ]]; then
    print -u2 -- "Failed VM retained for inspection: $WORK_VM"
  else
    delete_vm "$WORK_VM"
    print "tart: deleted disposable VM $WORK_VM; golden image $BASE_VM untouched"
  fi
  remove_boot_dir "$RUN_BOOT_DIR"
  [[ -z $RUN_ID ]] || rm -f "$RUNS_DIR/$RUN_ID.pid"
}

run_cmd() {
  local kind=$1 repo= has_repo=0 helper log_name result_dir
  local run_pid watchdog exit_code
  shift

  [[ ${1:-} == --repo ]] && {
    [[ $# -ge 2 ]] || die "--repo requires a path"
    repo=${2:A}
    has_repo=1
    shift 2
  }
  [[ ${1:-} == -- ]] || die "separate command arguments with --"
  shift
  [[ $# -gt 0 ]] || die "no command arguments supplied"
  (( has_repo == 0 )) || [[ -d $repo ]] || die "repository does not exist: $repo"
  [[ $kind == command || $has_repo == 1 ]] || die "$kind requires --repo PATH"

  prepare_dirs
  refuse_unsafe_state
  (( has_repo == 0 )) || preflight_repo "$repo"
  need_tart
  vm_exists "$BASE_VM" || die "base VM is missing; run prepare"

  RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$$"
  WORK_VM=${TART_XCUI_WORK_VM:-tart-xcui-run-$RUN_ID}
  result_dir="$RESULTS/$RUN_ID"
  mkdir -p "$result_dir"
  RUN_RESULT_DIR=$result_dir
  RUN_TART_LOG="$STATE/$RUN_ID.tart.log"
  RUN_BOOT_DIR=$(fresh_boot_dir "$RUN_ID")
  if [[ $kind == command ]]; then
    helper=run-command.sh
    log_name=command.log
  else
    helper=run-xcode.sh
    log_name=xcodebuild.log
  fi
  cp "$REFERENCES/$helper" "$result_dir/$helper"
  print "results: $result_dir"

  # Register before the first Tart mutation. A host failure during clone or
  # boot must leave durable evidence for the next invocation to fail closed on.
  print $$ >"$RUNS_DIR/$RUN_ID.pid"

  # The lock covers only the clone: cheap, and it serializes against image
  # promotion. The long build/test phase runs unlocked so runs can overlap.
  # Generous wait: an image operation may hold the lock for several minutes.
  lock_runner 900
  print "tart: cloning golden image $BASE_VM -> disposable VM $WORK_VM"
  tart clone "$BASE_VM" "$WORK_VM"
  unlock_runner

  trap 'RUN_EXIT_CODE=130; cleanup_work_vm; exit 130' INT TERM HUP
  local run_args=(--no-graphics --dir="artifacts:$result_dir")
  (( has_repo == 0 )) || run_args+=(--dir="source:${repo}:ro")
  print "tart: booting $WORK_VM headless; the host stays free"
  # Tart 2.34.0 resolves its control socket relative to the launch directory
  # and can fail to remove stale sockets there (openai/tart#1224). Run and
  # exec from one unique runner-owned directory, never the caller's repo.
  tart_from "$RUN_BOOT_DIR" run "${run_args[@]}" "$WORK_VM" >"$RUN_TART_LOG" 2>&1 &
  run_pid=$!
  wait_for_agent "$WORK_VM" "$run_pid" "$RUN_BOOT_DIR" ||
    die "working VM failed to start; see $RUN_TART_LOG"
  print "tart: guest ready — macOS $(tart_from "$RUN_BOOT_DIR" exec "$WORK_VM" /usr/bin/sw_vers -productVersion 2>/dev/null)" \
    "($(tart_from "$RUN_BOOT_DIR" exec "$WORK_VM" /usr/bin/sw_vers -buildVersion 2>/dev/null)), running in the VM"

  (
    sleep "$RUN_TIMEOUT"
    print -u2 -- "run timed out after ${RUN_TIMEOUT}s"
    tart stop "$WORK_VM" --timeout 10 >/dev/null 2>&1 || true
  ) >>"$RUN_TART_LOG" 2>&1 &
  watchdog=$!

  set +e
  if [[ $kind == command ]]; then
    tart_from "$RUN_BOOT_DIR" exec "$WORK_VM" /bin/zsh \
      "/Volumes/My Shared Files/artifacts/$helper" "$RUN_ID" "$has_repo" "$@" \
      2>&1 | tee "$result_dir/$log_name"
  else
    tart_from "$RUN_BOOT_DIR" exec "$WORK_VM" /bin/zsh \
      "/Volumes/My Shared Files/artifacts/$helper" "$RUN_ID" "$kind" "$@" \
      2>&1 | tee "$result_dir/$log_name"
  fi
  exit_code=${pipestatus[1]}
  set -e

  # tart exec does not reliably propagate the guest command's exit status;
  # the guest helper writes the authoritative code to the shared artifacts dir.
  local guest_status=
  [[ ! -f "$result_dir/guest-exit-status" ]] ||
    guest_status=$(<"$result_dir/guest-exit-status")
  [[ $guest_status != <-> ]] || exit_code=$guest_status

  kill "$watchdog" >/dev/null 2>&1 || true
  wait "$watchdog" >/dev/null 2>&1 || true
  stop_vm "$WORK_VM"
  wait "$run_pid" >/dev/null 2>&1 || true
  print "$exit_code" >"$result_dir/exit-status"
  [[ -d "$result_dir/Result.xcresult" ]] &&
    print "xcresult: $result_dir/Result.xcresult"
  RUN_EXIT_CODE=$exit_code
  cleanup_work_vm
  trap - INT TERM HUP
  return "$exit_code"
}

reset_cmd() {
  local vm
  for vm in $(tart list --source local -q | grep '^tart-xcui-run' || true); do
    stop_vm "$vm"
    delete_vm "$vm"
  done
  stop_vm "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  rm -f "$RUNS_DIR"/*.pid(N)
  print "Disposable VM state reset; base preserved: $BASE_VM"
}

reset_entry() {
  local acknowledge=0
  while (( $# )); do
    case $1 in
      --acknowledge-host-crash) acknowledge=1; shift ;;
      *) die "unknown reset argument: $1" ;;
    esac
  done
  prepare_dirs
  record_interrupted_run_state
  if [[ -f $HOST_CRASH_QUARANTINE ]] && (( ! acknowledge )); then
    die "host crash quarantine is active; inspect the recorded diagnostic, then use 'reset --acknowledge-host-crash' to explicitly accept recovery"
  fi
  need_tart
  lock_runner 60
  ensure_no_active_runs 0
  reset_cmd
  if (( acknowledge )); then
    rm -f "$HOST_CRASH_QUARANTINE"
    print "Host crash quarantine acknowledged and cleared"
  fi
}

clean_cmd() {
  local results_days= images=0 cache_days=30
  while (( $# )); do
    case $1 in
      --results) [[ ${2:-} == <-> ]] || die "--results requires DAYS"; results_days=$2; shift 2 ;;
      --images) images=1; shift ;;
      *) die "unknown clean argument: $1" ;;
    esac
  done

  reset_cmd
  rm -f "$STATE"/*.log(N) "$STATE"/*.tart.log(N)
  print "clean: removed state logs"
  tart prune --entries caches --older-than "$cache_days" || true
  print "clean: pruned OCI/IPSW caches not used in $cache_days days"
  if [[ -n $results_days ]]; then
    find "$RESULTS" -mindepth 1 -maxdepth 1 -type d -mtime +"$results_days" \
      -exec rm -rf {} + 2>/dev/null || true
    print "clean: removed results older than $results_days days"
  fi
  if (( images )); then
    stop_vm "$PREVIOUS_VM"
    delete_vm "$PREVIOUS_VM"
    rm -rf "$DATA_HOME/vm-share/cache"/*(N) 2>/dev/null || true
    print "clean: removed rollback image $PREVIOUS_VM and installer archives"
    print "clean: next rollback is unavailable until the next promotion"
  fi
  print "golden images (delete unused ones with: tart delete NAME):"
  tart list --source local 2>/dev/null | sed -n '1p;/tart-xcui-base/p'
  df -h "$TART_HOME" | tail -1
}

rollback_cmd() {
  vm_exists "$PREVIOUS_VM" || die "no previous golden image is available"
  stop_vm "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  tart clone "$PREVIOUS_VM" "$CANDIDATE_VM"
  promote_candidate "$CANDIDATE_VM"
  delete_vm "$CANDIDATE_VM"
  print "Rolled back $BASE_VM; the replaced image is now $PREVIOUS_VM"
}

# Image operations hold the lock for their whole duration and drain active
# runs first (up to the wait budget). The lock fd stays open until exit.
exclusive() {
  local wait=$1
  shift
  prepare_dirs
  refuse_unsafe_state
  need_tart
  lock_runner 60
  ensure_no_active_runs "$wait"
  "$@"
}

RUNS_WAIT=${TART_XCUI_RUNS_WAIT:-1800}

case ${1:-help} in
  doctor) doctor ;;
  prepare) shift; exclusive "$RUNS_WAIT" prepare_base "$@" ;;
  add-platform) shift; exclusive "$RUNS_WAIT" add_xcode_items platform "$@" ;;
  add-component) shift; exclusive "$RUNS_WAIT" add_xcode_items component "$@" ;;
  run) shift; run_cmd command "$@" ;;
  build) shift; run_cmd build "$@" ;;
  xcui-test|test) shift; run_cmd xcui-test "$@" ;;
  smoke)
    run_cmd xcui-test --repo "$ROOT/fixtures/SmokeApp" -- \
      -project SmokeApp.xcodeproj -scheme SmokeApp test
    ;;
  reset) shift; reset_entry "$@" ;;
  clean) shift; exclusive 0 clean_cmd "$@" ;;
  rollback) shift 2>/dev/null || true; exclusive "$RUNS_WAIT" rollback_cmd ;;
  help|-h|--help) usage ;;
  *) usage; die "unknown command: $1" ;;
esac
