#!/bin/bash
# Clear stale Telegram polling session before gateway starts.
# Called as ExecStartPre in hermes-gateway.service.
# This prevents "polling conflict" restart loops on gateway crash/reload.
# Usage: HERMES_HOME=/home/rurouni/.hermes bash scripts/telegram-clear-session.sh

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=*** -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.
#    This releases Telegram's stale long-poll session from the previous process.
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
