#!/bin/bash
# Clear stale Telegram polling session before gateway starts.
# Called as ExecStartPre in hermes-gateway.service.
# This prevents "polling conflict" loops on gateway restart.

ENV_FILE="${HERMES_HOME:-$HOME/.hermes}/.env"
if [ ! -f "$ENV_FILE" ]; then
    echo "telegram-clear-session: .env not found at $ENV_FILE"
    exit 0
fi

TOKEN=$(grep -m1 '^TELEGRAM_BOT_TOKEN=' "$ENV_FILE" | cut -d= -f2- | tr -d '"'"'" )
if [ -z "$TOKEN" ]; then
    echo "telegram-clear-session: TELEGRAM_BOT_TOKEN not found in $ENV_FILE"
    exit 0
fi

API="https://api.telegram.org/bot${TOKEN}"

# 1. Delete webhook + drop pending updates
echo "telegram-clear-session: Calling deleteWebhook..."
curl -s --connect-timeout 5 --max-time 10 "${API}/deleteWebhook?drop_pending_updates=true" -o /dev/null -w "  HTTP %{http_code}\n"

# 2. Acknowledge all pending updates via getUpdates with a high offset
echo "telegram-clear-session: Calling getUpdates with high offset..."
curl -s --connect-timeout 5 --max-time 10 "${API}/getUpdates?offset=-1&timeout=1" -o /dev/null -w "  HTTP %{http_code}\n"

echo "telegram-clear-session: Done — Telegram stale session cleaned."
exit 0
