#!/usr/bin/env sh
# Build the Android device-link .so for both v1 targets (JNI-PLAN.md W3):
# arm64-v8a (real phones) + x86_64 (emulator). Output lands under
# rust/target/jniLibs/<abi>/libspt_mobile_link_android.so — the app milestone
# copies (or symlinks) that tree into app/src/main/jniLibs/.
#
#   ci/build-android.sh
#
# Needs: cargo-ndk (`cargo install cargo-ndk`), the two rustup targets
# (added below), and an NDK — discovered via ANDROID_NDK_HOME, or under
# $ANDROID_HOME/ndk/<newest>. The desktop gates (cargo build/test,
# traceable-reqs check) never need any of this; only this script does.
#
# [impl->REQ-DEVICE-LINK-IROH]
set -eu

repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)

command -v cargo-ndk >/dev/null 2>&1 || {
  echo "cargo-ndk not found: cargo install cargo-ndk" >&2
  exit 1
}

# cargo-ndk discovers the NDK itself from ANDROID_NDK_HOME / ANDROID_HOME;
# fail early with a useful message instead of deep inside the build.
if [ -z "${ANDROID_NDK_HOME:-}" ] && [ -z "${ANDROID_NDK_ROOT:-}" ] && [ -z "${ANDROID_HOME:-}" ]; then
  echo "no NDK: set ANDROID_NDK_HOME (or ANDROID_HOME with an ndk/ dir)" >&2
  echo "install: sdkmanager --install 'ndk;27.3.13750724'" >&2
  exit 1
fi

rustup target add aarch64-linux-android x86_64-linux-android

cd "$repo_root/rust"
cargo ndk -t arm64-v8a -t x86_64 -o target/jniLibs build --release -p spt-mobile-link-android

echo "built:"
ls -l target/jniLibs/arm64-v8a/libspt_mobile_link_android.so \
      target/jniLibs/x86_64/libspt_mobile_link_android.so
