#!/usr/bin/env bash
# Builds the Quest APK - see build-image/prepare-android-project.sh (which
# this calls) for how android/ gets scratch, patched copies of engine/ and
# gl4es-src/, the Android SDL2/SDL2_mixer/fluidsynth-lite/openxr prebuilts,
# and bundled assets staged in. Run via ../run-image.sh (or directly, if
# already inside this image - see the Makefile's `apk` target).
#
# Unlike build-engine.sh, this step needs network access: Gradle/AGP's
# own dependency resolution isn't prebuilt into the image (see
# build-image/Dockerfile's comment on that trade-off).
set -euo pipefail

REPO_ROOT="$(pwd)"
ANDROID_DIR="$REPO_ROOT/android"

bash "$REPO_ROOT/build-image/prepare-android-project.sh"

echo "== Determining version (shared with 'make package', see build-image/version.sh) =="
git config --global --add safe.directory "$REPO_ROOT" 2>/dev/null || true
VERSION="$("$REPO_ROOT/build-image/version.sh")"
# versionName (VERSION, above) can be anything, but Android's versionCode
# must be a positive, monotonically-increasing integer - the commit count
# is a simple, deterministic stand-in for that.
VERSION_CODE="$(git -C "$REPO_ROOT" rev-list --count HEAD)"
echo "Version: $VERSION (versionCode $VERSION_CODE)"

echo "== Building the APK (gradlew assembleDebug) =="
cd "$ANDROID_DIR"
./gradlew --no-daemon assembleDebug \
    "-PquestshockVersionName=$VERSION" "-PquestshockVersionCode=$VERSION_CODE"

APK="$ANDROID_DIR/app/build/outputs/apk/debug/app-debug.apk"
[ -f "$APK" ] || { echo "BUILD FAIL: $APK not found after assembleDebug" >&2; exit 1; }

mkdir -p "$REPO_ROOT/dist"
PKG_NAME="questshock-$VERSION-android-arm64.apk"
cp "$APK" "$REPO_ROOT/dist/$PKG_NAME"

echo "== Done =="
echo "APK: $REPO_ROOT/dist/$PKG_NAME"
