#!/usr/bin/env bash
# ============================================================================
# run_v4.sh — Arranca Evony Scout V4 (backend LOCAL + agente protobuf-directo).
#
# IMPORTANTE: V4 usa los MISMOS emuladores/cuentas que V3 (6000=W / 6002=E).
# El agente V4 y el de V3 NO pueden convivir en el mismo proceso Evony (dos
# scripts frida → conflicto). Por eso este script:
#   1) Para el backend de V3 (deja de reattachar su agente).
#   2) Reinicia Evony en el/los emulador(es) elegidos → limpia el script V3 cargado.
#   3) Lanza el backend V4 PÚBLICO (bind Tailscale:8772, la URL de V3), que attacha el agente V4.
# El backend de V3 puede re-arrancarse luego; V4 y V3 NO deben correr a la vez
# sobre el MISMO emulador. Para volver a V3: `cd evony-scout-v3-research && ./restart_v3_lowpower.sh`.
#
# Uso: ./run_v4.sh [W|E|both]   (default: both)
# ============================================================================
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
V3="$(cd "$HERE/../evony-scout-v3-research" && pwd)"
PY="/Applications/Xcode.app/Contents/Developer/usr/bin/python3"
FS_BIN_NAME="frida-server-17.9.10-android-arm64"
EVONY_ACT="com.topgamesinc.evony/com.topgamesinc.androidplugin.UnityActivity"
WHICH="${1:-both}"
log(){ echo "[v4] $*"; }

declare -a EMUS
case "$WHICH" in
  W) EMUS=("emulator-6000:W") ;;
  E) EMUS=("emulator-6002:E") ;;
  both|*) EMUS=("emulator-6000:W" "emulator-6002:E") ;;
esac

# 0) Materiales que V4 necesita y están gitignored (los tomo de V3 si faltan)
[ -f "$HERE/$FS_BIN_NAME" ] || { log "copiando frida-server de V3"; cp "$V3/$FS_BIN_NAME" "$HERE/" 2>/dev/null || log "  (no encontrado en V3 — el backend lo pusheará si está)"; }
[ -f "$HERE/users.json" ]   || { log "copiando users.json de V3 (login local)"; cp "$V3/users.json" "$HERE/" 2>/dev/null || log "  (sin users.json — crea uno o copia de V3 para tener login)"; }

# 1) Compilar agentes V4 si faltan
if [ ! -f "$HERE/agent_W.js" ] || [ ! -f "$HERE/agent_E.js" ]; then
  log "compilando agentes V4 (build_agents_v4.sh)…"
  bash "$HERE/build_agents_v4.sh"
fi

# 2) Parar el backend de V3 (para que no reattache su agente)
if pgrep -f "evony-scout-v3-research/iscout_web.py" >/dev/null 2>&1; then
  log "parando backend V3…"; pkill -f "evony-scout-v3-research/iscout_web.py" || true; sleep 2
fi
# parar cualquier backend V4 previo
pkill -f "evony-scout-v4/iscout_web.py" 2>/dev/null || true; sleep 1

# 3) Reiniciar Evony en los emuladores elegidos (limpia el script frida de V3) + asegurar frida-server
for pair in "${EMUS[@]}"; do
  serial="${pair%%:*}"; half="${pair##*:}"
  log "[$half/$serial] reiniciando Evony (limpia script V3) + frida-server…"
  adb -s "$serial" shell "su -c 'ls /data/local/tmp/frida-server'" >/dev/null 2>&1 || \
    adb -s "$serial" push "$HERE/$FS_BIN_NAME" /data/local/tmp/frida-server >/dev/null 2>&1 || true
  adb -s "$serial" shell "su -c 'chmod 755 /data/local/tmp/frida-server'" >/dev/null 2>&1 || true
  adb -s "$serial" shell "su -c 'netstat -anl 2>/dev/null | grep \":27042 \" | grep LISTEN'" >/dev/null 2>&1 || \
    adb -s "$serial" shell "su -c 'setsid /data/local/tmp/frida-server </dev/null >/dev/null 2>&1 &'" >/dev/null 2>&1 || true
  adb -s "$serial" shell am force-stop com.topgamesinc.evony >/dev/null 2>&1 || true
  sleep 2
  adb -s "$serial" shell am start -n "$EVONY_ACT" >/dev/null 2>&1 || true
done
log "esperando 35s a que Evony cargue (Unity/IL2CPP + login) antes de attachar…"
"$PY" - <<'PYSLEEP'
import time; time.sleep(35)
PYSLEEP

# 4) Lanzar el backend V4 LOCAL (attacha el agente V4 fresco)
log "lanzando backend V4 (red, reemplaza V3)…"
cd "$HERE"
# PÚBLICO (red): bind a la IP de Tailscale como hacía V3 (fallback 127.0.0.1 si Tailscale no está).
BIND="$(tailscale ip -4 2>/dev/null | head -1)"; [ -z "$BIND" ] && BIND="127.0.0.1"
lsof -ti :8772 2>/dev/null | xargs kill -9 2>/dev/null || true   # liberar la URL de V3 (8772)
ISCOUT_BIND="$BIND" nohup "$PY" "$HERE/iscout_web.py" > /tmp/evony_v4.log 2>&1 &
sleep 4
if pgrep -f "evony-scout-v4/iscout_web.py" >/dev/null; then
  log "backend V4 OK (PID $(pgrep -f 'evony-scout-v4/iscout_web.py' | head -1)) -> http://$BIND:8772  (PÚBLICO en red, reemplaza a V3)"
  log "log: tail -f /tmp/evony_v4.log"
else
  log "ERROR: backend V4 no arrancó — revisa /tmp/evony_v4.log"; tail -20 /tmp/evony_v4.log 2>/dev/null
fi
