#!/bin/bash
# vexor-notify - forwards Naemon events to Vexor notification dispatcher
# Intentionally lenient: never let log/IO failures kill the script.
set -uo pipefail
TOKEN_FILE=/etc/vexor/notify-token
API_URL="http://127.0.0.1:8080/api/v1/notify/dispatch-internal"
LOG=/var/log/vexor/notify.log
mkdir -p /var/log/vexor 2>/dev/null || true

[ -r "$TOKEN_FILE" ] || exit 0
TOKEN=$(cat "$TOKEN_FILE")

KIND="${1:-}"; shift || true
case "$KIND" in
  host)
    HOST="${1:-}"; STATE="${2:-}"; OUTPUT="${3:-}"
    DURATION="${4:-}"; LAST_CHANGE="${5:-0}"; LONG="${6:-}"
    PAYLOAD=$(python3 -c 'import json,sys; print(json.dumps({"host":sys.argv[1],"service":"","severity":sys.argv[2],"output":sys.argv[3],"duration":sys.argv[4],"last_state_change":int(sys.argv[5] or 0),"long_output":sys.argv[6]}))' "$HOST" "$STATE" "$OUTPUT" "$DURATION" "$LAST_CHANGE" "$LONG")
    ;;
  service)
    HOST="${1:-}"; DESC="${2:-}"; STATE="${3:-}"; OUTPUT="${4:-}"
    DURATION="${5:-}"; LAST_CHANGE="${6:-0}"; LONG="${7:-}"
    PAYLOAD=$(python3 -c 'import json,sys; print(json.dumps({"host":sys.argv[1],"service":sys.argv[2],"severity":sys.argv[3],"output":sys.argv[4],"duration":sys.argv[5],"last_state_change":int(sys.argv[6] or 0),"long_output":sys.argv[7]}))' "$HOST" "$DESC" "$STATE" "$OUTPUT" "$DURATION" "$LAST_CHANGE" "$LONG")
    ;;
  *) exit 0 ;;
esac

# Send first, record afterwards. These must stay separate: the dispatch used to
# live inside the redirection to $LOG, so on any machine where the log file was
# not writable by the user Naemon runs as, bash skipped the whole block and the
# notification was dropped without a trace - while still exiting 0.
RESPONSE=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' \
  -H "X-Internal-Token: $TOKEN" -d "$PAYLOAD" "$API_URL" 2>&1)
RC=$?

{
  echo "$(date -Is) SEND $KIND $PAYLOAD"
  [ "$RC" -eq 0 ] || echo "$(date -Is) FAIL curl rc=$RC $RESPONSE"
  echo
} >> "$LOG" 2>/dev/null || true

# A failed delivery must be visible even when the log file is not writable.
if [ "$RC" -ne 0 ]; then
  logger -t vexor-notify "dispatch failed rc=$RC $KIND $HOST" 2>/dev/null || true
fi
exit 0
