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

echo "This script installs Android command-line tools, creates an AVD, starts an emulator, builds and installs the app. You will be asked for sudo password for package installation."

# 1) system packages (requires sudo)
sudo apt update
sudo apt install -y openjdk-11-jdk unzip curl qemu-kvm libvirt-daemon-system libvirt-clients

export ANDROID_SDK_ROOT="$HOME/Android/Sdk"
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools"
cd /tmp

CLI_ZIP=commandlinetools-linux.zip
if [ ! -f "$CLI_ZIP" ]; then
  echo "Downloading Android command-line tools..."
  curl -L -o "$CLI_ZIP" https://dl.google.com/android/repository/commandlinetools-linux-9477386_latest.zip
fi

unzip -o "$CLI_ZIP" -d "$ANDROID_SDK_ROOT/cmdline-tools/temp"
rm -rf "$ANDROID_SDK_ROOT/cmdline-tools/latest"
mv "$ANDROID_SDK_ROOT/cmdline-tools/temp" "$ANDROID_SDK_ROOT/cmdline-tools/latest"

export PATH="$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools:$ANDROID_SDK_ROOT/emulator:$PATH"

echo "Installing SDK packages (this will download several hundred MB)..."
yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --sdk_root="$ANDROID_SDK_ROOT" "platform-tools" "platforms;android-33" "build-tools;33.0.0" "emulator" "system-images;android-33;google_apis;x86_64"

yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses --sdk_root="$ANDROID_SDK_ROOT"

AVD_NAME=aprs_avd
echo no | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/avdmanager" create avd -n "$AVD_NAME" -k "system-images;android-33;google_apis;x86_64" --force

echo "Starting emulator in background (log -> /tmp/emulator_aprs.log). This may take 1-3 minutes."
nohup "$ANDROID_SDK_ROOT/emulator/emulator" -avd "$AVD_NAME" -no-window -no-audio -gpu swiftshader_indirect &>/tmp/emulator_aprs.log &

echo "Waiting for emulator to boot..."
adb wait-for-device
for i in {1..60}; do
  BOOT_DONE=$(adb shell getprop sys.boot_completed 2>/dev/null | tr -d '\r') || BOOT_DONE=""
  if [ "$BOOT_DONE" = "1" ]; then
    echo "Emulator booted"
    break
  fi
  sleep 2
done

echo "Building app with Gradle wrapper (may take several minutes)..."
cd "$HOME/my_aprs_project/vs2"
chmod +x ./gradlew || true
./gradlew assembleDebug --no-daemon

APK_PATH="app/build/outputs/apk/debug/app-debug.apk"
if [ -f "$APK_PATH" ]; then
  echo "Installing APK to emulator..."
  adb install -r "$APK_PATH"
  adb shell am start -n com.example.aprs/.MainActivity || true
  echo "Done: app installed and launched on emulator"
  echo "If emulator has no window, you can run Android Studio emulator GUI or remove -no-window flag in this script to display it."
else
  echo "APK not found: $APK_PATH"
  exit 1
fi
