#!/usr/bin/env bash
# ============================================================================
# run_pixel.sh — Arranca el escáner sobre MÓVILES FÍSICOS (Pixel 7a), puerto 8773.
#
# INSTANCIA SEPARADA de evony-scout-v4/ (emuladores 6000/6002, puerto 8772). No se pisan:
# distinto directorio, distinto puerto, distinta caché y distintos dispositivos. Se pueden
# tener ambas corriendo a la vez, pero NO con las mismas cuentas de Evony (una cuenta no puede
# estar logueada en dos sitios).
#
#   W = 33201JEHN00951 (Pixel 7a, cuenta evony1_1939, Oeste X<=650)
#   E = 32241JEHN24574 (Pixel 7a, cuenta evony2_1939, Este  X>=650)
#
# Uso: ./run_pixel.sh [W|E|both]   (default: both)
# ============================================================================
set -e
HERE="$(cd "$(dirname "$0")" && 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"
PORT=8773
WHICH="${1:-both}"
log(){ echo "[pixel] $*"; }

# Serial USB por defecto; respaldos por red (persist.adb.tcp.port=5555, sobrevive a reinicios).
SCANNER_W="${SCANNER_W:-33201JEHN00951}"; W_WIFI="${W_WIFI:-192.168.0.30:5555}"
SCANNER_E="${SCANNER_E:-32241JEHN24574}"; E_WIFI="${E_WIFI:-192.168.0.31:5555}"

# Resuelve por dónde responde cada móvil: USB primero, si no por LAN.
resolve(){   # $1=serial preferido  $2=respaldo wifi
  if [ "$(adb -s "$1" get-state 2>/dev/null | tr -d '\r')" = "device" ]; then echo "$1"; return 0; fi
  adb connect "$2" >/dev/null 2>&1; sleep 2
  if [ "$(adb -s "$2" get-state 2>/dev/null | tr -d '\r')" = "device" ]; then echo "$2"; return 0; fi
  return 1
}
DW="$(resolve "$SCANNER_W" "$W_WIFI")" || { log "❌ el móvil W no responde ni por USB ni por LAN"; exit 1; }
DE="$(resolve "$SCANNER_E" "$E_WIFI")" || { log "❌ el móvil E no responde ni por USB ni por LAN"; exit 1; }

declare -a DEVS
case "$WHICH" in
  W) DEVS=("$DW:W") ;;
  E) DEVS=("$DE:E") ;;
  both|*) DEVS=("$DW:W" "$DE:E") ;;
esac

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

# 2) Parar SOLO el backend de esta instancia (no toca el V4 de emuladores)
pkill -f "evony-scout-pixel/iscout_web.py" 2>/dev/null || true
lsof -ti :$PORT 2>/dev/null | xargs kill -9 2>/dev/null || true
sleep 1

# 3) Preparar cada móvil: frida-server + pantalla despierta + Evony al frente
for pair in "${DEVS[@]}"; do
  serial="${pair%%:*}"; half="${pair##*:}"
  log "[$half/$serial] preparando…"
  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
  # Unity PAUSA la app con la pantalla apagada o en segundo plano, y el juego pierde su conexión
  # con el servidor SIN avisar (el escaneo sigue leyendo memoria y todo parece sano).
  adb -s "$serial" shell settings put global stay_on_while_plugged_in 3 >/dev/null 2>&1 || true
  adb -s "$serial" shell settings put system screen_off_timeout 1800000 >/dev/null 2>&1 || true
  adb -s "$serial" shell input keyevent KEYCODE_WAKEUP >/dev/null 2>&1 || true
  sleep 1
  adb -s "$serial" shell input swipe 540 1900 540 600 200 >/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) Backend. Bind a Tailscale para que Plesk pueda hacerle de proxy (con 127.0.0.1 daría 503).
BIND="$(tailscale ip -4 2>/dev/null | head -1)"; [ -z "$BIND" ] && BIND="127.0.0.1"
log "lanzando backend (bind $BIND:$PORT)…"
cd "$HERE"
SCANNER_W="$DW" SCANNER_E="$DE" ISCOUT_BIND="$BIND" nohup "$PY" "$HERE/iscout_web.py" > /tmp/evony_pixel.log 2>&1 &
sleep 5
if pgrep -f "evony-scout-pixel/iscout_web.py" >/dev/null; then
  log "backend OK (PID $(pgrep -f 'evony-scout-pixel/iscout_web.py' | head -1)) -> http://$BIND:$PORT"
  log "log: tail -f /tmp/evony_pixel.log"
else
  log "ERROR: no arrancó — revisa /tmp/evony_pixel.log"; tail -20 /tmp/evony_pixel.log 2>/dev/null
fi
