#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
#  Auto-arranque Evony Scout V3  (lo invoca el LaunchAgent com.lume.evony.scanner)
#  V3 research:  emulador evony1_1939:6000 (W) + evony2_1939:6002 (E)
#                backend iscout_web.py en :8772, bind a la IP de Tailscale (100.127.215.100)
#  Variante LOWPOWER (headless, -no-window): así corren los 2 emuladores de V3
#  junto al del bot (6004) sin saturar GPU/CPU. (Para V3 CON ventana: usar
#  ../restart_v3.sh en vez de ./restart_v3_lowpower.sh.)
#  restart_v3_lowpower.sh hace restart COMPLETO (mata+arranca emuladores+frida+Evony+backend), ~2-3 min.
#
#  OJO: V3 cold-bootea SIN snapshot -> el LOGIN de cada cuenta y ponerlas en el
#  mapa del mundo SIGUE SIENDO MANUAL. Esto solo sube la infraestructura.
#  (V3 usa 6000/6002/8772, independiente del bot en 6004/8780: conviven sin conflicto.)
# ─────────────────────────────────────────────────────────────────────────────
export PATH="/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"

LOG=/tmp/autostart_scanner.log
exec >>"$LOG" 2>&1
echo "================ $(date '+%F %T')  boot_scanner V3: INICIO ================"

# El backend V3 hace ISCOUT_BIND="$(tailscale ip -4)". Si Tailscale no está listo
# aún, caería a 127.0.0.1 (no accesible en remoto). Esperamos hasta ~5 min.
BIND_IP="100.127.215.100"
for i in $(seq 1 60); do
  if /opt/homebrew/bin/tailscale ip -4 2>/dev/null | grep -q "$BIND_IP"; then
    echo "[boot_scanner] Tailscale IP $BIND_IP lista (intento $i)"
    break
  fi
  echo "[boot_scanner] esperando Tailscale ($BIND_IP)... intento $i/60"
  sleep 5
done

# Respiro para que el emulador-snapshot del bot (6004) coja ventaja y no competir
# los 3 emuladores por CPU/disco en el mismo instante.
sleep 15

cd /Users/danicosta/Desktop/Evony/evony-scout-v3-research || { echo "[boot_scanner] FALTA dir V3"; exit 1; }
echo "[boot_scanner] lanzando restart_v3_lowpower.sh (V3 headless: 6000+6002, backend 8772)"
bash ./restart_v3_lowpower.sh
echo "================ $(date '+%F %T')  boot_scanner V3: FIN ================"
