#!/bin/bash
# Healthcheck for Mosquitto

# Check if the container is running
if ! docker ps --filter "name=mosquitto" --filter "status=running" | grep -q "mosquitto"; then
    echo "[FAIL] Mosquitto container is not running"
    if command -v emit_event >/dev/null 2>&1; then
        emit_event "service_unhealthy" "error" "healthcheck.sh" "mosquitto" "$(date +%s)" "{\"reason\": \"container_not_running\"}"
    fi
    exit 1
fi

# Basic port check for 1883
if ! (echo > /dev/tcp/localhost/1883) >/dev/null 2>&1; then
    echo "[FAIL] Mosquitto port 1883 is not reachable"
    if command -v emit_event >/dev/null 2>&1; then
        emit_event "service_unhealthy" "error" "healthcheck.sh" "mosquitto" "$(date +%s)" "{\"reason\": \"port_unreachable\", \"port\": 1883}"
    fi
    exit 1
fi

echo "[OK] Mosquitto is healthy"
if command -v emit_event >/dev/null 2>&1; then
    # Optional: could emit service_recovered if it was previously unhealthy
    # For now, just a generic healthcheck_success or similar if needed, 
    # but the requirements mentioned service_recovered.
    # Logic for recovery usually requires state.
    emit_event "service_recovered" "info" "healthcheck.sh" "mosquitto" "$(date +%s)" "{\"status\": \"healthy\"}"
fi
exit 0
