#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

PID_FILE="ouptsw/realtime_stream.pid"
if [[ ! -f "$PID_FILE" ]]; then
  printf 'Realtime stream is not running: missing %s\n' "$PID_FILE"
  exit 0
fi

PID="$(cat "$PID_FILE")"
if [[ -z "$PID" ]] || ! kill -0 "$PID" 2>/dev/null; then
  rm -f "$PID_FILE"
  printf 'Realtime stream is not running. Removed stale pid file.\n'
  exit 0
fi

kill "$PID"
sleep 1
pkill -f "avfoundation -framerate 2.0 -i 3:none" 2>/dev/null || true
pkill -f "ffplay .*WeChat Vision ONNX Preview" 2>/dev/null || true
rm -f "$PID_FILE"
printf 'Realtime stream stopped: pid=%s\n' "$PID"
