#!/bin/sh
# Vaultr boundary-test helper
#
# This helper records evidence for a scoped Local Mode test. It does not prove
# universal zero egress and it does not inspect matter content. Run it on a
# dedicated test machine while the fixed workflow is executed.
#
# Usage: sh vaultr-boundary-test.sh <VAULTR_PID> [output-directory]

set -eu

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
  printf '%s\n' "Usage: sh vaultr-boundary-test.sh <VAULTR_PID> [output-directory]" >&2
  exit 64
fi

PID="$1"
OUT="${2:-vaultr-boundary-evidence-$(date +%Y%m%d-%H%M%S)}"
mkdir -p "$OUT"

if ! kill -0 "$PID" 2>/dev/null; then
  printf '%s\n' "Process $PID is not running." >&2
  exit 66
fi

{
  printf '%s\n' "Vaultr boundary test — evidence capture"
  printf 'Started: %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
  printf 'PID: %s\n' "$PID"
  printf '%s\n' "Scope: one process, one machine, one workload; inspect before making any claim."
  printf '%s\n' "Exceptions: updater/model downloads only when explicitly started."
} > "$OUT/README.txt"

sw_vers > "$OUT/os.txt"
system_profiler SPHardwareDataType > "$OUT/hardware.txt"
ps -p "$PID" -o pid=,ppid=,comm=,args= > "$OUT/process.txt"
lsof -nP -a -p "$PID" -i > "$OUT/sockets-before.txt" || true

printf '%s\n' "Capture started in $OUT. Run the fixed Local Mode workflow now." >&2
printf '%s\n' "Press Ctrl-C when the workflow is complete; packet captures will be closed." >&2

TCPDUMP_EN0="$OUT/vaultr-en0.pcap"
TCPDUMP_LO0="$OUT/vaultr-loopback.pcap"

cleanup() {
  if [ -n "${EN0_PID:-}" ]; then kill "$EN0_PID" 2>/dev/null || true; fi
  if [ -n "${LO0_PID:-}" ]; then kill "$LO0_PID" 2>/dev/null || true; fi
  if [ -n "${EN0_PID:-}" ]; then wait "$EN0_PID" 2>/dev/null || true; fi
  if [ -n "${LO0_PID:-}" ]; then wait "$LO0_PID" 2>/dev/null || true; fi
  lsof -nP -a -p "$PID" -i > "$OUT/sockets-after.txt" || true
  date -u '+%Y-%m-%dT%H:%M:%SZ' > "$OUT/finished-at.txt"
  printf '%s\n' "Evidence saved to $OUT. Review the files and pcap contents; no result is asserted by this helper." >&2
}
trap cleanup INT TERM EXIT

if command -v tcpdump >/dev/null 2>&1; then
  sudo tcpdump -i en0 -nn -tttt -w "$TCPDUMP_EN0" >/dev/null 2>"$OUT/tcpdump-en0.log" &
  EN0_PID=$!
  sudo tcpdump -i lo0 -nn -tttt -w "$TCPDUMP_LO0" >/dev/null 2>"$OUT/tcpdump-lo0.log" &
  LO0_PID=$!
else
  printf '%s\n' "tcpdump is not available; socket and system evidence was still collected." > "$OUT/tcpdump-unavailable.txt"
fi

while kill -0 "$PID" 2>/dev/null; do
  date -u '+%Y-%m-%dT%H:%M:%SZ' >> "$OUT/heartbeat.txt"
  lsof -nP -a -p "$PID" -i >> "$OUT/sockets.log" || true
  sleep 5
done
