#!/usr/bin/env bash
# ───────────────────────────────────────────────────────────────────────────
#  Evony Scout v2 DUAL — RESTART TOTAL
#  Mata TODO (backend, frida-server, Evony) y rearranca limpio.
#  Uso: ./restart_v2.sh
#  El cache_persist.json se PRESERVA (no se borra).
# ───────────────────────────────────────────────────────────────────────────
set -u
DIR=/Users/danicosta/Desktop/Evony/evony-scout-dual
FS="$DIR/frida-server-17.9.10-android-arm64"
PORT=8771

echo "== RESTART TOTAL =="

# 1) Matar backend
echo "[..] matando backend..."
ps aux | grep -E "iscout_web|start_v2" | grep -v grep | awk '{print $2}' | xargs -r kill -9 2>/dev/null
sleep 2

# 2) Matar frida-server en ambos emuladores
echo "[..] matando frida-server..."
for d in emulator-5554 emulator-5556; do
  for pid in $(adb -s "$d" shell "pidof frida-server" 2>/dev/null | tr -d '\r' | tr ' ' '\n'); do
    adb -s "$d" shell "kill -9 $pid" 2>/dev/null
  done
done
sleep 3

# 3) Force-stop Evony (sí, esto genera pop-ups, pero garantiza estado limpio
#    para que el bundle 167KB se cargue sin timeout)
echo "[..] force-stop Evony en ambos emuladores..."
for d in emulator-5554 emulator-5556; do
  adb -s "$d" shell "am force-stop com.topgamesinc.evony" 2>/dev/null
done
sleep 4

# 4) Reset adb (resuelve corrupción del transport)
echo "[..] adb reset..."
adb kill-server 2>/dev/null
sleep 2
adb start-server >/dev/null 2>&1
sleep 3
adb devices

# 5) Relanzar frida-server
echo "[..] relanzando frida-server..."
for d in emulator-5554 emulator-5556; do
  adb -s "$d" shell "nohup /data/local/tmp/frida-server >/dev/null 2>&1 &" 2>/dev/null
done
sleep 4
for d in emulator-5554 emulator-5556; do
  fpid=$(adb -s "$d" shell "pidof frida-server" 2>/dev/null | tr -d '\r')
  echo "  $d frida-server pid=[$fpid]"
done

# 6) Relanzar Evony (estado fresco evita el "frida-server timeout" en bundle 167KB)
echo "[..] relanzando Evony..."
for d in emulator-5554 emulator-5556; do
  adb -s "$d" shell "am start -n com.topgamesinc.evony/com.topgamesinc.androidplugin.UnityActivity" >/dev/null 2>&1
done
echo "[..] esperando 30s a Evony..."
sleep 30

# 7) Lanzar backend
echo "[..] lanzando backend..."
cd "$DIR" && nohup /Applications/Xcode.app/Contents/Developer/usr/bin/python3 iscout_web.py >/tmp/evony_dual.log 2>&1 &
sleep 5

# 8) Verificación final
echo ""
echo "== resultado =="
ps aux | grep iscout_web | grep -v grep | awk '{print "  backend pid="$2}' | head -1
echo "  UI: http://127.0.0.1:$PORT"
echo ""
echo "[!] CIERRA las pop-ups iniciales (City Development, Battle Deal) en ambos emuladores"
echo "    y ve al World Map. Luego la captura empezará."
echo ""
echo "log: tail -f /tmp/evony_dual.log"
echo "stop: lsof -ti :$PORT | xargs kill -9"
