#!/usr/bin/env bash
# android_emulator_stop — Para uno o todos los emuladores Android via adb emu kill.
set -euo pipefail

android_emulator_stop() {
    local serial="${1:-}"
    local ADB="${ADB:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk/platform-tools/adb.exe}"
    local killed=0

    if [[ -z "$serial" ]]; then
        # Detectar todos los emuladores activos
        local serials
        serials=$("$ADB" devices 2>/dev/null | grep -E '^emulator-' | awk '{print $1}' || true)

        if [[ -z "$serials" ]]; then
            echo "android_emulator_stop: no running emulators found"
            return 0
        fi

        while IFS= read -r s; do
            [[ -z "$s" ]] && continue
            echo "android_emulator_stop: stopping $s"
            "$ADB" -s "$s" emu kill 2>/dev/null || true
            ((killed++)) || true
        done <<< "$serials"
    else
        echo "android_emulator_stop: stopping $serial"
        "$ADB" -s "$serial" emu kill 2>/dev/null || true
        ((killed++)) || true
    fi

    echo "android_emulator_stop: stopped $killed emulator(s)"
    return 0
}

# Ejecutar si se llama directamente
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    android_emulator_stop "${1:-}"
fi
