#!/usr/bin/env bash
# Auto-start the Hermes worker watchdog if it's not running.
# Called by a Hermes cron job or launchd every minute.
# Place this in ~/.hermes/scripts/ on the worker machine.

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WATCHDOG_SCRIPT="$SCRIPT_DIR/hermes-worker-watchdog.sh"

# Already running? Check if a worker process exists
if pgrep -f "hermes-worker.js" > /dev/null 2>&1; then
  exit 0  # All good
fi

# Not running — start the watchdog in background
cd "$(dirname "$WATCHDOG_SCRIPT")" || exit 1
export HOME="${HOME:-$(eval echo ~)}"
export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:$PATH"
nohup bash "$WATCHDOG_SCRIPT" >> /tmp/hermes-worker-watchdog.log 2>&1 &
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Worker watchdog started (PID $!)" >> /tmp/hermes-worker-watchdog.log
