#!/bin/bash
# Monit → Telegram alert script for opendeviationbar
# Deployed to /usr/local/bin/obdpy-monit-alert.sh
#
# Reads credentials from the same local.env used by systemd services.
# Monit sets MONIT_HOST, MONIT_SERVICE, MONIT_EVENT, MONIT_DESCRIPTION,
# MONIT_DATE as environment variables before calling this script.

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: OPENDEVIATIONBAR_TELEGRAM_TOKEN or OPENDEVIATIONBAR_TELEGRAM_CHAT_ID not set" >&2
    exit 1
fi

TEXT="$(cat <<EOF
<b>MONIT ALERT</b>
<b>Host:</b> ${MONIT_HOST:-unknown}
<b>Service:</b> ${MONIT_SERVICE:-unknown}
<b>Event:</b> ${MONIT_EVENT:-unknown}
<b>Description:</b> ${MONIT_DESCRIPTION:-no description}
<b>Date:</b> ${MONIT_DATE:-unknown}
EOF
)"

curl -s -X POST "https://api.telegram.org/bot${OPENDEVIATIONBAR_TELEGRAM_TOKEN}/sendMessage" \
    -d chat_id="${OPENDEVIATIONBAR_TELEGRAM_CHAT_ID}" \
    -d parse_mode="HTML" \
    -d text="${TEXT}" > /dev/null
