#!/bin/bash
# Build and run the Android test app on an emulator.
# The gradle 'installRunDebug' task does the launch, logcat scrape and pass/fail
# reporting; this only handles emulator lifecycle.
set -euo pipefail
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd "$SCRIPTDIR/.."

SDK=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}
EMULATOR="$SDK/emulator/emulator"
ADB="$SDK/platform-tools/adb"
[ -x "$EMULATOR" ] || { echo "emulator not found at $EMULATOR (set ANDROID_HOME)" >&2; exit 1; }
# the gradle installRun task shells out to a bare 'adb', so it has to be on PATH
export ANDROID_HOME="$SDK"
export PATH="$SDK/platform-tools:$SDK/emulator:$PATH"

BOOT_TIMEOUT=${BOOT_TIMEOUT:-300}
# extra emulator flags, e.g. '-no-accel' on a host with no hardware acceleration
EMULATOR_ARGS=${EMULATOR_ARGS:-}
emulator_pid=""

cleanup() {
    if [ -n "$emulator_pid" ]; then
        echo "=== stopping emulator ==="
        kill "$emulator_pid" 2>/dev/null || true
    fi
}
trap cleanup EXIT

if [ -z "$("$ADB" devices | sed -n 's/\(emulator-[0-9]*\)[[:space:]]*device$/\1/p')" ]; then
    AVD=${AVD:-$("$EMULATOR" -list-avds | head -1)}
    [ -n "$AVD" ] || { echo "no AVD available; create one in Android Studio" >&2; exit 1; }
    echo "=== booting AVD: $AVD ==="
    # shellcheck disable=SC2086
    "$EMULATOR" -avd "$AVD" -no-window -no-audio -no-snapshot -no-boot-anim $EMULATOR_ARGS &
    emulator_pid=$!

    "$ADB" wait-for-device
    deadline=$((SECONDS + BOOT_TIMEOUT))
    until [ "$("$ADB" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" == "1" ]; do
        [ $SECONDS -lt $deadline ] || { echo "emulator did not finish booting in ${BOOT_TIMEOUT}s" >&2; exit 1; }
        sleep 2
    done
    echo "=== boot complete ==="
else
    echo "=== using already-running emulator ==="
fi

cd android_test
exec ./gradlew installRunDebug
