#!/usr/bin/env bash
# ───────────────────────────────────────────────────────────────────────────
#  Evony Scout v1  —  1 emulador (emulator-5554 / cuenta #1) · puerto 8770
#  Arranque rápido: levanta emulador + frida-server + backend.
#  (El login de Evony y poner la cuenta en el mapa del mundo lo haces TÚ.)
# ───────────────────────────────────────────────────────────────────────────
set -u
EMU=/opt/homebrew/share/android-commandlinetools/emulator/emulator
DIR=/Users/danicosta/Desktop/Evony/iscout
FS="$DIR/frida-server-17.9.10-android-arm64"
PORT=8770

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 v1 (single) =="
kill_port 8771 && echo "[..] v2 (8771) detenido — v1 y v2 NO pueden correr a la vez"
kill_port "$PORT"
ensure_emu evony_root 5554
ensure_frida emulator-5554
adb -s emulator-5554 shell "am start -n com.topgamesinc.evony/com.topgamesinc.androidplugin.UnityActivity" >/dev/null 2>&1

cat <<'MANUAL'

[!] MANUAL en emulator-5554:
    · sesión iniciada en la CUENTA #1
    · en el MAPA DEL MUNDO, server 2163
    · ventana del emulador VISIBLE (Unity pausa el render sin foco)

MANUAL

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