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

cd "$(dirname "$0")"
mkdir -p ouptsw

PID_FILE="ouptsw/wechat_window_live.pid"
LOG_FILE="ouptsw/wechat_window_live.log"

if [[ -f "$PID_FILE" ]]; then
  OLD_PID="$(cat "$PID_FILE")"
  if [[ -n "$OLD_PID" ]] && kill -0 "$OLD_PID" 2>/dev/null; then
    printf 'WeChat window live stream is already running: pid=%s\n' "$OLD_PID"
    printf 'Open http://127.0.0.1:8765/\n'
    exit 0
  fi
fi

nohup ./venv/bin/python wechat_window_live.py \
  --fps 60 \
  --infer-interval 3 \
  --confidence 0.05 \
  --target-class 0 \
  --host 127.0.0.1 \
  --port 8765 \
  --open-browser \
  > "$LOG_FILE" 2>&1 &

PID="$!"
printf '%s' "$PID" > "$PID_FILE"

printf 'WeChat window live stream started: pid=%s\n' "$PID"
printf 'Open http://127.0.0.1:8765/\n'
printf 'Stream http://127.0.0.1:8765/stream.mjpg\n'
printf 'Log: %s\n' "$LOG_FILE"
