#!/usr/bin/env bash
# Install the monolith watchdog as a macOS LaunchAgent.
# Run once after install or reboot: ./scripts/install-watchdog.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PLIST="$PROJECT_DIR/platforms/macos/com.mercadodevida.monolith-watchdog.plist"
DEST_DIR="$HOME/Library/LaunchAgents"
DEST="$DEST_DIR/com.mercadodevida.monolith-watchdog.plist"

echo "[INFO] Installing monolith watchdog service..."

# Stop existing instance if any
if launchctl list | grep -q com.mercadodevida.monolith-watchdog; then
  echo "[INFO] Stopping existing watchdog..."
  launchctl unload "$DEST" 2>/dev/null || true
fi

mkdir -p "$DEST_DIR"
cp "$PLIST" "$DEST"
launchctl load "$DEST"
echo "[OK] Watchdog installed and loaded. PID: $(launchctl list | grep com.mercadodevida.monolith-watchdog | awk '{print $1}')"

# Start services immediately too
"$SCRIPT_DIR/monolith.sh" prod restart
