#!/usr/bin/env bash
set -e

if [ -z "$DISPLAY" ]; then
  echo "No X DISPLAY set. Cannot start GUI emulator here."
  echo "If you are on a remote session, run this on a desktop with X or use SSH -X." 
  exit 1
fi

SDK="$HOME/Android/Sdk"
ADB="$SDK/platform-tools/adb"
EMULATOR_BIN="$SDK/emulator/emulator"
AVD_NAME=aprs_avd
LOG=/tmp/emulator_aprs_gui.log

echo "Killing existing emulator instances..."
pkill -f 'emulator' || true
sleep 1

if [ ! -x "$ADB" ]; then
  echo "adb not found at $ADB"; exit 1
fi

echo "Restarting adb..."
$ADB kill-server || true
sleep 1
$ADB start-server || true

if [ ! -x "$EMULATOR_BIN" ]; then
  echo "Emulator binary not found: $EMULATOR_BIN"; exit 1
fi

echo "Starting emulator '$AVD_NAME' (GUI). Log -> $LOG"
"$EMULATOR_BIN" -avd "$AVD_NAME" -partition-size 5120 -gpu host -wipe-data -no-boot-anim &>"$LOG" &
EMUPID=$!
echo "Emulator PID: $EMUPID"

echo "Waiting for adb to see emulator..."
for i in $(seq 1 60); do
  LIST=$($ADB devices | sed -n '2,200p' | tr -d '\r' || true)
  if echo "$LIST" | grep -q 'emulator'; then
    echo "Emulator connected to adb"
    break
  fi
  echo "Waiting for adb... ($i)"
  sleep 2
done

echo "Waiting for emulator to finish boot (up to 240s)..."
for i in $(seq 1 120); do
  BOOT=$($ADB shell getprop sys.boot_completed 2>/dev/null | tr -d '\r' || true)
  if [ "$BOOT" = "1" ]; then
    echo "Emulator booted after $((i*2))s"
    break
  fi
  echo "Boot waiting... ($i)"
  sleep 2
done

echo "--- emulator log tail ---"
tail -n 200 "$LOG" || true

echo "Building app..."
cd "$HOME/my_aprs_project/vs2"
chmod +x ./gradlew || true
./gradlew assembleDebug --no-daemon

APK="app/build/outputs/apk/debug/app-debug.apk"
if [ -f "$APK" ]; then
  echo "Installing APK"
  $ADB install -r "$APK" || true
  $ADB shell am start -n com.example.aprs/.MainActivity || true
  echo "App launched on emulator (check window)."
else
  echo "APK not found: $APK"
  exit 1
fi

echo "Done. ADB devices:"; $ADB devices -l
