#!/bin/bash
# Monit self-heartbeat: sends a periodic Telegram message proving monit is alive.
# Deployed to /usr/local/bin/obdpy-monit-heartbeat.sh
# Called by Monit's "check program" as uid "tca" every 30 cycles (~15 min).
# Exit 0 = heartbeat sent successfully.
#
# Runs as tca via monit's `as uid "tca"` directive, so the mode-600
# local.env is readable without root. Uses monit's HTTP API on
# localhost:2812 (no auth) to get service counts instead of the
# `monit` CLI (which requires root access to monitrc).

set -euo pipefail

ENV_FILE="/home/tca/opendeviationbar-py/deploy/opendeviationbar.local.env"

if [ ! -f "$ENV_FILE" ]; then
    echo "ERROR: $ENV_FILE not found" >&2
    exit 1
fi

# shellcheck source=/dev/null
source "$ENV_FILE"

# Also source the git-tracked env for CHAT_ID
GIT_ENV="/home/tca/opendeviationbar-py/deploy/opendeviationbar.env"
if [ -f "$GIT_ENV" ]; then
    # shellcheck source=/dev/null
    source "$GIT_ENV"
fi

if [ -z "${OPENDEVIATIONBAR_TELEGRAM_TOKEN:-}" ] || [ -z "${OPENDEVIATIONBAR_TELEGRAM_CHAT_ID:-}" ]; then
    echo "ERROR: Telegram credentials not set" >&2
    exit 1
fi

# Query monit HTTP API (localhost:2812, no auth) for service count.
# The XML status page lists all monitored services; count those with status=0 (OK).
MONIT_SUMMARY=$(curl -s "http://localhost:2812/_status?format=xml" 2>/dev/null \
    | grep -c '<status>0</status>' || echo "?")

TEXT="$(cat <<EOF
<b>MONIT HEARTBEAT</b>
<b>Host:</b> $(hostname)
<b>Services OK:</b> ${MONIT_SUMMARY}
<b>Time:</b> $(date -u '+%Y-%m-%d %H:%M:%S UTC')
EOF
)"

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
    "https://api.telegram.org/bot${OPENDEVIATIONBAR_TELEGRAM_TOKEN}/sendMessage" \
    -d chat_id="${OPENDEVIATIONBAR_TELEGRAM_CHAT_ID}" \
    -d parse_mode="HTML" \
    -d disable_notification="true" \
    -d text="${TEXT}")

if [ "$HTTP_CODE" = "200" ]; then
    echo "Heartbeat sent (${MONIT_SUMMARY} services OK)"
    exit 0
else
    echo "Telegram API returned HTTP ${HTTP_CODE}" >&2
    exit 1
fi
