#!/bin/sh
# Forced command для пуш-ключей хостов за NAT (authorized_keys: command="~/bin/pushgw-ingest <instance>").
# Клиент передаёт только имя job (ssh ... <job>), метрики — в stdin в text-формате Prometheus.
# instance задаётся ключом, а не клиентом: хост не может писать метрики от чужого имени.
#
# Особый «job» `health` — только чтение: внешний сторож (rpi, monwatch) раз в час проверяет,
# что сам мониторинг fr1 жив. Отдаёт строки key=value, ничего не меняет.
instance="$1"
job="$SSH_ORIGINAL_COMMAND"
case "$instance" in ""|*[!a-z0-9_-]*) echo "bad instance" >&2; exit 2;; esac

if [ "$job" = health ]; then
  code() { curl -s -o /dev/null -w '%{http_code}' --max-time 10 "$1"; }
  echo "prometheus_healthy=$(code http://127.0.0.1:9090/-/healthy)"
  echo "alertmanager_healthy=$(code http://127.0.0.1:9093/-/healthy)"
  echo "pushgateway_healthy=$(code http://127.0.0.1:9091/-/healthy)"
  # видит ли Prometheus свежие пуши этого хоста — сквозная проверка pushgateway → scrape → TSDB
  age=$(curl -s --max-time 10 http://127.0.0.1:9090/api/v1/query \
        --data-urlencode "query=time() - max(push_time_seconds{instance=\"$instance\"})" \
        | python3 -c 'import json,sys
try: print(int(float(json.load(sys.stdin)["data"]["result"][0]["value"][1])))
except Exception: print(-1)')
  echo "push_age_seconds=$age"
  # счётчики доставки в Telegram (монотонные; сторож сравнивает с прошлым замером)
  curl -s --max-time 10 http://127.0.0.1:9093/metrics | awk '
    /^alertmanager_notifications_failed_total\{integration="telegram"/ {f+=$2}
    /^alertmanager_notifications_total\{integration="telegram"/ {t+=$2}
    END {printf "tg_notifications_total=%d\ntg_notifications_failed_total=%d\n", t, f}'
  firing=$(curl -s --max-time 10 http://127.0.0.1:9093/api/v2/alerts?active=true | python3 -c 'import json,sys
try: print(len(json.load(sys.stdin)))
except Exception: print(-1)')
  echo "alerts_active=$firing"
  exit 0
fi

case "$job" in ""|*[!a-z0-9_]*) echo "bad job" >&2; exit 2;; esac
exec curl -sS --fail-with-body --max-time 30 -X PUT --data-binary @- \
  "http://127.0.0.1:9091/metrics/job/$job/instance/$instance"
