#!/usr/bin/env bash
# Cron every minute: if the agent tmux session died, alert Ahmed on Telegram and relaunch.
set -u
STATE=/root/tools/.watchdog-state
ENVFILE=/root/.claude/channels/telegram/.env
CHATFILE=/root/tools/.agent-chat-id
if tmux has-session -t agent 2>/dev/null; then rm -f "$STATE"; exit 0; fi
if [ ! -f "$STATE" ]; then
  touch "$STATE"
  if [ -f "$ENVFILE" ] && [ -f "$CHATFILE" ]; then
    TOKEN=$(grep -o "TELEGRAM_BOT_TOKEN=.*" "$ENVFILE" | cut -d= -f2- | tr -d "\"")
    CHAT=$(cat "$CHATFILE")
    curl -s -m 10 "https://api.telegram.org/bot${TOKEN}/sendMessage" \
      -d chat_id="${CHAT}" -d text="⚠️ Ultron agent was down — restarting it now." >/dev/null
  fi
fi
/root/tools/agent-launch.sh
