#!/bin/bash
# Builds Android (arm64) wheels for the engine packages that have C or Rust code
# and no Android wheel on PyPI. Publish the output folder at the "wheels" URL in
# runtime/python-android.json, then run lock_android.py on it.
#
#   Android/scripts/build_wheels.sh <output-folder>
#
# Needs: cibuildwheel 4.3+, Rust with the aarch64-linux-android target, the
# Android SDK at $ANDROID_HOME with NDK 27.3.13750724, and a JDK in $JAVA_HOME.
set -euo pipefail

OUT=$(mkdir -p "$1" && cd "$1" && pwd)
SCRIPTS=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
NDK="$ANDROID_HOME/ndk/27.3.13750724/toolchains/llvm/prebuilt/$(uname -s | tr A-Z a-z)-x86_64"
MANIFEST="$(dirname "$0")/../runtime/python-android.json"
# The wheels must match the Python the app installs: cp314 for 3.14.x (they link libpython3.14 by name).
TAG=$(python3 -c "import json,sys; v=json.load(open(sys.argv[1]))['version'].split('.'); print('cp'+v[0]+v[1])" "$MANIFEST")

# Same versions as Desktop/runtime/requirements-windows.lock.
PACKAGES=(cffi==2.1.1 cryptography==50.0.2 qh3==1.9.4 pycryptodome==3.23.0 pylzss==0.3.4 lzfse==0.4.2.post1 zeroconf==0.151.5)

# Python's headers and libpython, for extensions that link it explicitly.
url=$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['arm64-v8a']['url'])" "$MANIFEST")
curl -fsSL "$url" -o "$WORK/python.tgz"
mkdir "$WORK/python" && tar xzf "$WORK/python.tgz" -C "$WORK/python" ./prefix
PREFIX="$WORK/python/prefix"
VERSION=$(ls "$PREFIX/include" | grep -m1 '^python3')

# cffi needs libffi; CPython's Android build links its own copy statically.
curl -fsSL https://github.com/beeware/cpython-android-source-deps/releases/download/libffi-3.4.4-3/libffi-3.4.4-3-aarch64-linux-android.tar.gz \
    -o "$WORK/libffi.tgz"
mkdir "$WORK/libffi" && tar xzf "$WORK/libffi.tgz" -C "$WORK/libffi"

# On Android an extension module only finds Python's symbols if it links
# libpython itself; Rust (PyO3) abi3 extensions do not by default. Rust also
# links with 4 KB pages unless told otherwise; 16 KB-page devices refuse that (BEA-211).
export CIBW_ENVIRONMENT="CPATH=$PREFIX/include/$VERSION:$WORK/libffi/include LIBRARY_PATH=$WORK/libffi/lib \
BINDGEN_EXTRA_CLANG_ARGS='--sysroot=$NDK/sysroot --target=aarch64-linux-android24' \
RUSTFLAGS='-C link-arg=-L$PREFIX/lib -C link-arg=-l$VERSION -C link-arg=-Wl,-z,max-page-size=16384'"
export CIBW_TEST_SKIP="*"

cd "$WORK"
for spec in "${PACKAGES[@]}"; do
    name=${spec%%==*}
    pip3 download -q --no-deps --no-binary :all: "$spec" -d sdists
    archive=$(ls sdists/"$name"-"${spec##*==}".tar.gz)
    tar xzf "$archive" -C .
    cibuildwheel --only "$TAG-android_arm64_v8a" --output-dir "$OUT" "$(basename "$archive" .tar.gz)"
done
ls -l "$OUT"
# Every library must load on 16 KB-page devices (BEA-211).
python3 -B "$SCRIPTS/page_size.py" "$OUT"/*.whl
