#!/bin/bash
# ───────────────────────────────────────────────────────────────────────────
#  BrockHQ keeper watchdog — starts presence.py if it isn't already running.
#  Covers crashes AND reboots (cron runs after boot). No root needed.
#
#  Install (user crontab — `crontab -e`), check every 5 minutes:
#     */5 * * * * /bin/bash /usr/www/brockweb/brockhq/keepalive.sh
#  (optional, faster boot recovery)
#     @reboot     /bin/bash /usr/www/brockweb/brockhq/keepalive.sh
# ───────────────────────────────────────────────────────────────────────────
DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR" || exit 1

# Already running? Nothing to do.
pgrep -f "$DIR/presence.py" >/dev/null 2>&1 && exit 0

# Prefer the venv Python (has websockets + pymysql); fall back to system python3.
PY="$DIR/.venv/bin/python"
[ -x "$PY" ] || PY="python3"

nohup "$PY" "$DIR/presence.py" >> "$DIR/presence.log" 2>&1 &
echo "[keepalive] started presence.py with $PY at $(date -u '+%Y-%m-%d %H:%M:%S')Z" >> "$DIR/presence.log"
