#!/usr/bin/env bash
# Reinicio completo del banco de pruebas híbrido (emulator-6008 / AVD evony_hibrid).
#
# Lo invocan DOS rutas de recuperación del backend:
#   · el botón "↻ Reload Bot" de la UI  -> /api/reload
#   · el watchdog cuando el relaunch en caliente no arranca el render -> _cold_boot()
#
# Deja emulador + frida-server + juego listos. NO reinicia el backend: éste sigue vivo
# (ese es el sentido de "Stop Bot": el backend aguanta) y su watchdog re-attacha solo en
# cuanto el juego vuelve a estar arriba y se ha borrado el sentinel .bot_stopped.
#
# Es idempotente: si el emulador o frida ya están arriba, no los toca; sólo trae el juego
# al frente. Así vale tanto para un Stop ligero (juego cerrado, emulador vivo) como para
# un apagado total del emulador.
set -u
# MESH: honra BOT_EMULATOR/BOT_AVD para que cada nodo reinicie SU dispositivo (no siempre el
# 6008). Sin las envs, defaults idénticos al banco híbrido original.
#   · EMULADOR (serial emulator-NNNN): se puede cold-boot con `emulator -avd`; el -port debe
#     casar con el serial (emulator-6008 -> 6008).
#   · FÍSICO (Pixel: serial de dispositivo o IP:puerto): NO se cold-boot un teléfono; si no
#     está en adb sólo se avisa. Los pasos de frida + juego valen igual para ambos.
DEV="${BOT_EMULATOR:-emulator-6008}"
AVD="${BOT_AVD:-evony_hibrid}"
case "$DEV" in
  emulator-*) IS_EMU=1; EMU_PORT="${DEV#emulator-}" ;;
  *)          IS_EMU=0; EMU_PORT="" ;;
esac
PKG="com.topgamesinc.evony"
ACT="com.topgamesinc.androidplugin.UnityActivity"
SDK="/opt/homebrew/share/android-commandlinetools"
log(){ echo "[full_restart] $*"; }

# 1) DISPOSITIVO — cold boot SÓLO si es emulador y no está en adb (Stop Bot lo pudo apagar).
#    A un Pixel físico no se le lanza `emulator`: si está caído es intervención manual.
if ! adb devices | grep -q "^${DEV}[[:space:]]*device"; then
  if [ "$IS_EMU" = "1" ]; then
    log "emulador $DEV caído -> cold boot (-port $EMU_PORT)"
    nohup "$SDK/emulator/emulator" -avd "$AVD" -port "$EMU_PORT" \
      -no-snapshot-load -no-snapshot-save -no-boot-anim -gpu host -no-audio \
      > "/tmp/hibrid_emulator_${EMU_PORT}.log" 2>&1 &
    for i in $(seq 1 70); do
      [ "$(adb -s "$DEV" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ] && { log "boot completado"; break; }
      sleep 3
    done
  else
    log "⚠️ dispositivo FÍSICO $DEV no está en adb -> no se puede cold-boot un teléfono; requiere conexión manual (USB/adb connect). Continuo por si vuelve."
  fi
else
  log "dispositivo $DEV ya arriba"
fi

# 2) FRIDA-SERVER — arrancarlo sólo si está caído (necesita root: sale el diálogo Magisk
#    UNA vez si el emulador venía de un apagado total)
if ! adb -s "$DEV" shell "ps -A 2>/dev/null | grep -q frida-server"; then
  log "frida-server caído -> arrancando (setsid, root)"
  adb -s "$DEV" shell "su -c 'setsid /data/local/tmp/frida-server </dev/null >/dev/null 2>&1 &'" >/dev/null 2>&1 &
  sleep 4
else
  log "frida-server ya vivo"
fi

# 3) JUEGO al frente (si ya corría, sólo lo trae al primer plano — inofensivo)
log "lanzando Evony"
adb -s "$DEV" shell "am start -n $PKG/$ACT" >/dev/null 2>&1 || true

log "listo — el backend re-attacha solo en cuanto la cuenta cargue"
