#!/usr/bin/env bash
# hermes-worker-watchdog.sh
#
# Wraps hermes-worker.js in a restart loop.
# If the worker exits (connection lost, registry wiped, heartbeat failed),
# this script restarts it with a fresh registration after a short delay.
#
# Usage: bash hermes-worker-watchdog.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# launchd/cron provide a minimal PATH; hermes is usually in ~/.local/bin
export HOME="${HOME:-$(eval echo ~)}"
export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:$PATH"

echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Watchdog started"

while true; do
  echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Starting worker..."
  node "$SCRIPT_DIR/hermes-worker.js"
  EXIT_CODE=$?

  echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Worker exited (code $EXIT_CODE) — restarting in 5s..."
  sleep 5
done
