#!/usr/bin/env bash
# Monitor a TCP port's listener PID and record when it disappears.
# Usage:
#   bash scripts/monitor/port-kill-watch.sh <port> [label]
# Output log:
#   /tmp/routecodex-port-watch-<port>-<timestamp>.log

set -euo pipefail

PORT=${1:-}
LABEL=${2:-}

if [[ -z "$PORT" ]]; then
  echo "Usage: $0 <port> [label]" >&2
  exit 2
fi

if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then
  echo "Invalid port: $PORT" >&2
  exit 2
fi

TS=$(date +%Y%m%d-%H%M%S)
LOG_FILE="/tmp/routecodex-port-watch-${PORT}-${TS}.log"
INTERVAL_MS=500

log() {
  echo "[$(date +%Y-%m-%dT%H:%M:%S%z)] $*" | tee -a "$LOG_FILE" >/dev/null
}

resolve_pid() {
  lsof -t -nP -iTCP:"$PORT" -sTCP:LISTEN 2>/dev/null | head -n 1 || true
}

log "watch start port=${PORT} label=${LABEL:-none} log=${LOG_FILE}"

PID=$(resolve_pid)
if [[ -z "$PID" ]]; then
  log "no listener detected on port ${PORT}"
  exit 1
fi

log "listener pid=${PID}"

while true; do
  if ! kill -0 "$PID" 2>/dev/null; then
    log "listener pid ${PID} exited"
    break
  fi
  CURRENT=$(resolve_pid)
  if [[ -z "$CURRENT" ]]; then
    log "listener on port ${PORT} vanished (pid=${PID})"
    break
  fi
  if [[ "$CURRENT" != "$PID" ]]; then
    log "listener pid changed ${PID} -> ${CURRENT}"
    PID="$CURRENT"
  fi
  sleep 0.5
done

log "capturing recent logs (last 2m, syslog style)"
log "--- log show (filtered) ---"
/usr/bin/log show --last 2m --style syslog 2>/dev/null \
  | grep -i -E "killed|kill|SIGKILL|SIGTERM|routecodex|node|memorystatus|jetsam" \
  | tail -n 200 \
  | tee -a "$LOG_FILE" >/dev/null || true
log "--- end ---"

log "capturing process snapshot"
ps -Ao pid,ppid,state,etime,comm,args | grep -E "(routecodex|node|dist/index.js)" | tee -a "$LOG_FILE" >/dev/null || true

log "done"

