#!/bin/bash
# Monit -> Telegram LOUD failure alert with UUID and diagnostics.
# Deployed to /usr/local/bin/obdpy-monit-alert.sh
#
# Called by Monit on ANY service failure. Sends IMMEDIATELY with sound.
# Includes: UUID, service details, recent journal logs, system snapshot.
#
# Monit sets these environment variables before calling:
#   MONIT_HOST, MONIT_SERVICE, MONIT_EVENT, MONIT_DESCRIPTION, MONIT_DATE

set -euo pipefail

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

[ -f "$ENV_FILE" ] && source "$ENV_FILE"
[ -f "$GIT_ENV" ] && source "$GIT_ENV"

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

UUID=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || python3 -c 'import uuid; print(uuid.uuid4())')

SERVICE="${MONIT_SERVICE:-unknown}"
EVENT="${MONIT_EVENT:-unknown}"
DESCRIPTION="${MONIT_DESCRIPTION:-no description}"
HOST="${MONIT_HOST:-unknown}"
DATE="${MONIT_DATE:-unknown}"

# Get package version
PKG_VERSION=$("$VENV/bin/python3" -c 'from opendeviationbar import __version__; print(__version__)' 2>/dev/null || echo "unknown")

# Try to get recent journal logs for the failed service
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"

# Map monit service name to systemd unit
case "$SERVICE" in
    sidecar)    UNIT="opendeviationbar-sidecar" ;;
    kintsugi)   UNIT="opendeviationbar-kintsugi" ;;
    *)          UNIT="" ;;
esac

if [ -n "$UNIT" ]; then
    RECENT_LOGS=$(journalctl --user -u "$UNIT" --no-pager -n 8 --output=short-iso 2>/dev/null \
        | tail -8 | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g' || echo "(logs unavailable)")
else
    RECENT_LOGS="(no systemd unit for $SERVICE)"
fi

# System snapshot
MEM_INFO=$(free -h 2>/dev/null | awk '/^Mem:/ {printf "RAM %s/%s (%s free)", $3, $2, $4}' || echo "?")
LOAD_INFO=$(cat /proc/loadavg 2>/dev/null | awk '{printf "load [%s %s %s]", $1, $2, $3}' || echo "?")
DISK_INFO=$(df -h / 2>/dev/null | awk 'NR==2 {printf "disk %s/%s (%s free)", $3, $2, $4}' || echo "?")

# Query monit for a quick status summary of all services
MONIT_SUMMARY=$("$VENV/bin/python3" -c '
import urllib.request, xml.etree.ElementTree as ET
try:
    with urllib.request.urlopen("http://localhost:2812/_status?format=xml", timeout=5) as r:
        root = ET.fromstring(r.read())
    svcs = root.findall("service")
    ok = sum(1 for s in svcs if s.findtext("status") == "0")
    failed = [s.findtext("name") for s in svcs if s.findtext("status") != "0"]
    print(f"{ok}/{len(svcs)} OK" + (f" | FAILED: {\", \".join(failed)}" if failed else ""))
except Exception:
    print("(monit API error)")
' 2>/dev/null || echo "(monit API unavailable)")

read -r -d '' TEXT <<EOF || true
<b>BUG ALERT  MONIT FAILURE</b>
<code>${UUID}</code>

<b>Service:</b> ${SERVICE}
<b>Event:</b> ${EVENT}
<b>Description:</b> ${DESCRIPTION}
<b>Host:</b> ${HOST}
<b>Time:</b> ${DATE}
<b>Version:</b> v${PKG_VERSION}

<b>System Snapshot:</b>
${MEM_INFO} | ${LOAD_INFO}
${DISK_INFO}

<b>All Services:</b> ${MONIT_SUMMARY}

<b>Recent Logs (${SERVICE}):</b>
<pre>${RECENT_LOGS}</pre>
EOF

# Send LOUD — disable_notification=false (sound ON)
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 disable_notification="false" \
    --data-urlencode "text=${TEXT}" > /dev/null

echo "Alert sent for ${SERVICE}: ${EVENT} ($UUID)"
