#!/bin/bash

# SENTINEL/SAR Monitoring & Auto-Restart Script
# Run via cron every 5 minutes to ensure SAR stays running

SAR_DIR="/home/hugo/.openclaw/workspace/toolpillar/sovereign-ai-router"
PID_FILE="$SAR_DIR/sar.pid"
LOG_FILE="$SAR_DIR/logs/monitor.log"

check_and_restart() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Check if PID file exists
    if [ ! -f "$PID_FILE" ]; then
        echo "[$timestamp] PID file missing. Starting SAR..." >> "$LOG_FILE"
        "$SAR_DIR/start-sar.sh" >> "$LOG_FILE" 2>&1
        return
    fi
    
    # Check if process is running
    local pid=$(cat "$PID_FILE")
    if ! ps -p $pid > /dev/null 2>&1; then
        echo "[$timestamp] SAR process (PID: $pid) not running. Restarting..." >> "$LOG_FILE"
        "$SAR_DIR/start-sar.sh" >> "$LOG_FILE" 2>&1
        return
    fi
    
    # SAR is running
    echo "[$timestamp] SAR is running (PID: $pid)" >> "$LOG_FILE"
}

check_and_restart
