#!/bin/bash
# /root/watchdog_realtime_daemons.sh
#
# Checks each realtime_daemon.php instance via its PID file.
# If the PID file is missing or the process is dead, restarts the daemon.
# Intended to run every 5 minutes via root crontab:
#
#   */5 * * * * /root/watchdog_realtime_daemons.sh >> /var/log/realtime_watchdog.log 2>&1

DAEMON=/home/faretrak/public_html/todis_ext/realtime_daemon.php
PHP=/usr/local/bin/php
LOGDIR=/home/faretrak/public_html/todis_ext/logs
PIDDIR=/home/faretrak/public_html/todis_ext/run

# Format: "domain_arg|pid_file|log_file"
INSTANCES=(
    "38767|realtime_38767.pid|realtime_38767.log"
    "43332,43349|realtime_43332_43349.pid|realtime_43332_43349.log"
    "90091|realtime_90091.pid|realtime_90091.log"
    "90092|realtime_90092.pid|realtime_90092.log"
    "44270|realtime_44270.pid|realtime_44270.log"
    "80081|realtime_80081.pid|realtime_80081.log"
)

TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

for entry in "${INSTANCES[@]}"; do
    IFS='|' read -r DOMAINS PIDFILE LOGFILE <<< "$entry"
    PIDPATH="$PIDDIR/$PIDFILE"
    LOGPATH="$LOGDIR/$LOGFILE"

    RUNNING=0

    if [[ -f "$PIDPATH" ]]; then
        PID=$(cat "$PIDPATH")
        if [[ -n "$PID" ]] && kill -0 "$PID" 2>/dev/null; then
            RUNNING=1
        fi
    fi

    if [[ "$RUNNING" -eq 1 ]]; then
        echo "[$TIMESTAMP] OK   domains=$DOMAINS pid=$PID"
    else
        echo "[$TIMESTAMP] DEAD domains=$DOMAINS — restarting..."
        nohup "$PHP" "$DAEMON" "--datadomain=$DOMAINS" >> "$LOGPATH" 2>&1 &
        NEWPID=$!
        echo "[$TIMESTAMP] STARTED domains=$DOMAINS pid=$NEWPID"
    fi
done
