e2e_remote_run() {
  set -m
  local port=$1 waitsec=$2 srv=$3 mkdirs=$4
  shift 4
  probe() { (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; }
  if [ -z "$srv" ]; then
    if [ -n "$mkdirs" ]; then
      while IFS= read -r d; do [ -n "$d" ] && mkdir -p "$d"; done <<<"$mkdirs"
    fi
    "$@"
    local rc0=$?
    echo "e2e-remote: client exit=$rc0 (no server; $(hostname))"
    return $rc0
  fi
  if probe; then
    echo "e2e-remote: FATAL port $port already in use on $(hostname)" >&2
    return 3
  fi
  if [ -n "$mkdirs" ]; then
    while IFS= read -r d; do [ -n "$d" ] && mkdir -p "$d"; done <<<"$mkdirs"
  fi
  # pg/log stay global: the EXIT trap fires after this frame is gone, and a
  # local would be unset by then, turning the teardown into a no-op.
  log=$(mktemp -t e2e-remote-server.XXXXXX)
  bash -c "$srv" >"$log" 2>&1 &
  pg=$!
  cleanup() {
    kill -TERM "-$pg" 2>/dev/null || true
    for _ in 1 2 3 4 5 6 7 8 9 10; do
      kill -0 "-$pg" 2>/dev/null || return 0
      sleep 0.5
    done
    kill -KILL "-$pg" 2>/dev/null || true
  }
  trap cleanup EXIT INT TERM
  local i=0
  until probe; do
    if ! kill -0 "$pg" 2>/dev/null; then
      echo "e2e-remote: FATAL server exited before listening on $port" >&2
      tail -60 "$log" >&2
      return 4
    fi
    i=$((i + 1))
    if [ "$i" -ge "$waitsec" ]; then
      echo "e2e-remote: FATAL server never listened on $port within ${waitsec}s" >&2
      tail -60 "$log" >&2
      return 5
    fi
    sleep 1
  done
  echo "e2e-remote: server ready on 127.0.0.1:$port after ${i}s ($(hostname))"
  "$@"
  local rc=$?
  echo "e2e-remote: client exit=$rc"
  return $rc
}
