#!/bin/bash
HEALTH_URL=http://127.0.0.1:8080/health
FAILURE_FILE=/tmp/ibsystem2mqtt_failures
MAX_FAILURES=3

if curl -sf --max-time 5 "$HEALTH_URL" > /dev/null 2>&1; then
    echo 0 > "$FAILURE_FILE"
else
    FAILURES=$(cat "$FAILURE_FILE" 2>/dev/null || echo 0)
    FAILURES=$((FAILURES + 1))
    echo $FAILURES > "$FAILURE_FILE"
    if [ $FAILURES -ge $MAX_FAILURES ]; then
        systemctl restart ibsystem2mqtt
        echo 0 > "$FAILURE_FILE"
    fi
fi

AVAIL=$(mosquitto_sub -h 192.168.50.151 -p 1883 -u mqtt -P mqtt123 \
  -t ibsystem/bridge/availability -C 1 --quiet 2>/dev/null)
if [ "$AVAIL" = "offline" ] && systemctl is-active --quiet ibsystem2mqtt; then
    logger -t ibsystem_watchdog "availability=offline - restarting"
    systemctl restart ibsystem2mqtt
fi
