#!/usr/bin/env bash
# ───────────────────────────────────────────────────────────────────────────
#  Evony Scout v2 DUAL  —  2 emuladores · puerto 8771
#    W = emulator-5554 (AVD evony_root,   cuenta #1)  → mitad Oeste  X≤650
#    E = emulator-5556 (AVD evony_root_2, cuenta #2)  → mitad Este   X≥650
#  Arranque rápido: levanta ambos emuladores + frida-server + backend.
#  (El login de Evony y poner ambas cuentas en el mapa del mundo lo haces TÚ.)
# ───────────────────────────────────────────────────────────────────────────
set -u
EMU=/opt/homebrew/share/android-commandlinetools/emulator/emulator
DIR=/Users/danicosta/Desktop/Evony/evony-scout-dual
FS="$DIR/frida-server-17.9.10-android-arm64"
PORT=8771

kill_port(){ local p; p=$(lsof -ti :"$1" 2>/dev/null); [ -n "$p" ] && kill -9 $p 2>/dev/null; }
wait_boot(){ until [ "$(adb -s "$1" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ]; do sleep 4; done; }

ensure_emu(){ local avd=$1 port=$2
  if adb devices | grep -q "emulator-${port}[[:space:]]*device"; then
    echo "[ok] emulator-${port} ya activo"; return; fi
  echo "[..] lanzando AVD ${avd} en puerto ${port} (puede tardar)"
  nohup "$EMU" -avd "$avd" -port "$port" -no-snapshot -writable-system \
    -no-boot-anim -gpu auto -memory 8192 -partition-size 8192 -no-audio \
    >/tmp/emu_${port}.log 2>&1 &
  sleep 5; wait_boot "emulator-${port}"; echo "[ok] emulator-${port} arrancado"
}

ensure_frida(){ local s=$1
  adb -s "$s" root >/dev/null 2>&1; sleep 2
  if [ -n "$(adb -s "$s" shell pidof frida-server 2>/dev/null | tr -d '\r')" ]; then
    echo "[ok] frida-server activo en ${s}"; return; fi
  adb -s "$s" shell "[ -f /data/local/tmp/frida-server ]" 2>/dev/null \
    || adb -s "$s" push "$FS" /data/local/tmp/frida-server >/dev/null
  adb -s "$s" shell "chmod 755 /data/local/tmp/frida-server" 2>/dev/null
  adb -s "$s" shell "nohup /data/local/tmp/frida-server >/dev/null 2>&1 &" 2>/dev/null
  sleep 3; echo "[ok] frida-server arrancado en ${s}"
}

echo "== Evony Scout v2 DUAL =="
kill_port 8770 && echo "[..] v1 (8770) detenido — v1 y v2 NO pueden correr a la vez"
kill_port "$PORT"
ensure_emu evony_root   5554
ensure_emu evony_root_2 5556
ensure_frida emulator-5554
ensure_frida emulator-5556

# Arrancar Evony SOLO si no está corriendo. Sin force-stop: si ya estabas en el
# world map, se preserva la posición de cámara y NO aparecen los pop-ups iniciales
# (City Development, Battle Deal, etc.) que bloquean el broadcast del world map.
# Si Evony está en un estado degradado (raro tras cold-boot), el watchdog del
# backend lo detecta y fuerza un re-attach.
for d in emulator-5554 emulator-5556; do
  pid=$(adb -s "$d" shell "pidof com.topgamesinc.evony" 2>/dev/null | tr -d '\r')
  if [ -z "$pid" ]; then
    echo "[..] Evony no corre en $d, lanzando..."
    adb -s "$d" shell "am start -n com.topgamesinc.evony/com.topgamesinc.androidplugin.UnityActivity" >/dev/null 2>&1
    NEEDS_WAIT=1
  else
    echo "[ok] Evony ya corre en $d (pid=$pid) — preservando estado"
  fi
done
if [ -n "${NEEDS_WAIT:-}" ]; then
  echo "[..] esperando 25s a que Evony arranque..."
  sleep 25
else
  sleep 3
fi

cat <<'MANUAL'

[!] MANUAL (login y cuentas SIEMPRE manuales):
    emulator-5554 → CUENTA #1 · mapa del mundo · server 2163
    emulator-5556 → CUENTA #2 · mapa del mundo · server 2163
                    (la #2 entra por su vínculo NO-Google: Facebook/etc.
                     Google Play NO autentica en emulador rooteado google_apis)
    · AMBAS ventanas de emulador VISIBLES (Unity pausa el render sin foco)
    · Si tocaste agent_sweep.ts, recompila los 2 agentes (ver README §Rebuild)

MANUAL

cd "$DIR" && nohup python3 iscout_web.py >/tmp/evony_dual.log 2>&1 &
sleep 4
echo "[ok] v2 -> http://127.0.0.1:8771"
echo "    log:  tail -f /tmp/evony_dual.log"
echo "    stop: lsof -ti :8771 | xargs kill -9"
