#!/bin/bash
# Hermes Telegram WEBHOOK watchdog (v2 2026-07-07; replaces the poll-probe v1
# which itself induced wedges via getUpdates conflicts).
# Webhook mode: Telegram pushes to nginx -> 127.0.0.1:8443. Checks are passive.
LOG=/root/.hermes/logs/poll-watchdog.log
TOK=$(grep -oE "^TELEGRAM_BOT_TOKEN=.*" /root/.hermes/.env | cut -d= -f2)
INFO=$(curl -sS -m 15 "https://api.telegram.org/bot$TOK/getWebhookInfo" 2>&1)
URL=$(echo "$INFO" | python3 -c "import json,sys; print(json.load(sys.stdin)[\"result\"].get(\"url\",\"\"))" 2>/dev/null)
ERRDATE=$(echo "$INFO" | python3 -c "import json,sys; print(json.load(sys.stdin)[\"result\"].get(\"last_error_date\",0))" 2>/dev/null)
NOW=$(date +%s)
if [ -z "$URL" ]; then
  echo "$(date -Is) webhook URL EMPTY -> restarting gateway" >> $LOG
  systemctl restart hermes-gateway; exit 0
fi
if [ -n "$ERRDATE" ] && [ "$ERRDATE" -gt 0 ] && [ $((NOW-ERRDATE)) -lt 600 ]; then
  # Telegram failed to deliver within the last 10 min -> local server likely dead
  if ! ss -tln | grep -q ":8443 "; then
    echo "$(date -Is) recent delivery error + port 8443 not listening -> restarting" >> $LOG
    systemctl restart hermes-gateway; exit 0
  fi
  echo "$(date -Is) recent delivery error but port up - watching: $(echo "$INFO" | head -c 200)" >> $LOG
fi
exit 0
