#!/usr/bin/env bash
# notify-failure UNIT - send last log lines of UNIT via every configured channel.
# Config (from /etc/default/notify-failure, mode 0600):
#   NOTIFY_WEBHOOK=https://...        generic JSON {"text": "..."} (Slack/Mattermost/Teams-compatible)
#   NOTIFY_NTFY_URL=https://ntfy.sh/topic   plain-text POST (optional NOTIFY_NTFY_TOKEN)
#   NOTIFY_EMAIL=ops@example.com      needs a working `mail` or `sendmail`
#   NOTIFY_LOG_LINES=30
# NOTIFY_DRY_RUN=1 prints the message instead of sending (used by tests).
set -uo pipefail
unit="${1:?usage: notify-failure UNIT}"
host="$(hostname -f 2>/dev/null || hostname)"
lines="${NOTIFY_LOG_LINES:-30}"
log="$(journalctl -u "$unit" -n "$lines" --no-pager -o cat 2>/dev/null || true)"
state="$(systemctl show -p Result,ExecMainStatus "$unit" 2>/dev/null | tr '\n' ' ' || true)"
subject="FAILED: $unit on $host"
body="$subject
${state}

${log}"

if [[ "${NOTIFY_DRY_RUN:-0}" == 1 ]]; then printf '%s\n' "$body"; exit 0; fi

sent=0 failed=0
if [[ -n "${NOTIFY_WEBHOOK:-}" ]]; then
    payload="$(python3 -c 'import json,sys; print(json.dumps({"text": sys.argv[1]}))' "$body")"
    if curl -fsS -m 10 -X POST -H 'Content-Type: application/json' --data "$payload" "$NOTIFY_WEBHOOK" >/dev/null
    then sent=1; else failed=1; fi
fi
if [[ -n "${NOTIFY_NTFY_URL:-}" ]]; then
    auth=(); [[ -n "${NOTIFY_NTFY_TOKEN:-}" ]] && auth=(-H "Authorization: Bearer $NOTIFY_NTFY_TOKEN")
    if curl -fsS -m 10 "${auth[@]}" -H "Title: $subject" -H 'Priority: high' -H 'Tags: warning' \
        --data-binary "$body" "$NOTIFY_NTFY_URL" >/dev/null
    then sent=1; else failed=1; fi
fi
if [[ -n "${NOTIFY_EMAIL:-}" ]]; then
    if command -v mail >/dev/null 2>&1; then
        if printf '%s\n' "$body" | mail -s "$subject" "$NOTIFY_EMAIL"; then sent=1; else failed=1; fi
    elif command -v sendmail >/dev/null 2>&1; then
        if printf 'To: %s\nSubject: %s\n\n%s\n' "$NOTIFY_EMAIL" "$subject" "$body" | sendmail -t; then sent=1; else failed=1; fi
    else echo "notify-failure: no mail/sendmail" >&2; failed=1; fi
fi
if (( sent == 0 && failed == 0 )); then
    echo "notify-failure: no channel configured; edit /etc/default/notify-failure" >&2
    exit 1
fi
exit $(( failed > 0 && sent == 0 ? 1 : 0 ))
