#!/bin/bash
# Restarts srebot-api + srebot-web and times the recovery milestones.
# Usage: bash scripts/restart-test.sh
set -u
T0=$(date +%s.%N)
echo "=== T0: $(date +%H:%M:%S.%3N) restarting srebot-api + srebot-web ==="
pm2 restart srebot-api srebot-web >/dev/null

echo "--- polling /health (every 0.5s until ready:true) ---"
for i in $(seq 1 120); do
  R=$(curl -sS --max-time 2 http://127.0.0.1:6000/health 2>/dev/null || true)
  if echo "$R" | grep -q '"ready":true'; then
    echo "ready at +$(echo "$(date +%s.%N) - $T0" | bc)s : $R"
    break
  fi
  sleep 0.5
done

echo "--- /api/squadrons/1066957 (first cold hit, separate connection) ---"
curl -sS -o /dev/null -w "  HTTP=%{http_code} time=%{time_total}s\n" "http://127.0.0.1:6000/api/squadrons/1066957"

echo "--- 4 leaderboards in parallel (heavyDb concurrent reads) ---"
for ep in stats squadrons players vehicles; do
  (curl -sS -o /dev/null -w "  $ep: HTTP=%{http_code} time=%{time_total}s\n" "http://127.0.0.1:6000/api/leaderboard/$ep") &
done
wait

echo "=== full warm at +$(echo "$(date +%s.%N) - $T0" | bc)s ==="
echo "--- pm2 status ---"
pm2 info srebot-api | grep -E "uptime|restart|status" | head -5
