#!/bin/bash
# Verify the heartbeat timer is active (user service for tca)
# Deployed to /usr/local/bin/obdpy-check-heartbeat-timer.sh
# Called by Monit's "check program" as uid "tca" — exit 0 = OK, exit 1 = alert
#
# Runs as tca via monit's `as uid "tca"` directive. Monit's as-uid is a
# bare setuid() — it does NOT set up a login session, so XDG_RUNTIME_DIR
# and DBUS_SESSION_BUS_ADDRESS must be set explicitly for systemctl --user.

set -euo pipefail

export XDG_RUNTIME_DIR="/run/user/$(id -u)"
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"

STATUS=$(systemctl --user is-active opendeviationbar-heartbeat.timer 2>/dev/null || true)

if [ "$STATUS" = "active" ]; then
    echo "heartbeat timer active"
    exit 0
else
    echo "heartbeat timer: ${STATUS:-unknown}"
    exit 1
fi
