#!/usr/bin/env bash
set -Eeuo pipefail

DIR="/workspace/rabbit-commander-agent"
SUP="$DIR/supervise-rabbit-agent.sh"
ENV="$DIR/agent.env"
LOG="$DIR/agent-supervisor.log"

echo "=================================================="
echo " Rabbit Commander RunPod Agent Repair"
echo "=================================================="

if [ ! -d "$DIR" ]; then
  echo "ERROR: $DIR not found"
  exit 1
fi
if [ ! -f "$ENV" ]; then
  echo "ERROR: $ENV not found"
  exit 1
fi
if [ ! -x "$SUP" ]; then
  chmod +x "$SUP" 2>/dev/null || true
fi

echo "Stopping stale Rabbit agent/supervisor processes..."
pkill -f '^node agent.js$' 2>/dev/null || true
pkill -f 'supervise-rabbit-agent.sh' 2>/dev/null || true
sleep 2

echo "Starting persistent Rabbit Commander supervisor..."
nohup bash "$SUP" >> "$DIR/supervisor-launch.log" 2>&1 &
sleep 5

echo
echo "=== PROCESS CHECK ==="
pgrep -af 'supervise-rabbit-agent|node agent.js' || true

echo
echo "=== LAST LOG LINES ==="
tail -30 "$LOG" 2>/dev/null || true

echo
echo "=== SAFE ENV CHECK ==="
grep -E '^RABBIT_COMMANDER_(RELAY|DEVICE_ID|ENABLE_SHELL)=' "$ENV" || true
echo "RABBIT_COMMANDER_TOKEN=<redacted>"

echo
echo "Repair completed."
