#!/usr/bin/env bash

set -e

mkdir build-host tools
cmake -S source -B build-host -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=tools -DPSEMEK_PACKAGE_MODE=ON -DPSEMEK_PACKAGE_HOST=ON -DPSEMEK_BACKEND=OFF
cmake --build build-host -t install -j

cp -r source/psemek/libs/android/app .

mkdir -p app/assets

mkdir -p build-target/arm64-v8a
cmake -S source -B build-target/arm64-v8a/build \
	-DCMAKE_BUILD_TYPE=Release -DANDROID_USE_LEGACY_TOOLCHAIN_FILE=ON -DANDROID_PLATFORM=34 -DANDROID_STL=c++_shared -DANDROID_CPP_FEATURES="rtti exceptions" \
	-DANDROID_ABI=arm64-v8a -DCMAKE_TOOLCHAIN_FILE="${NDK_ROOT}/build/cmake/android.toolchain.cmake" \
	-DCMAKE_FIND_ROOT_PATH="${BOOST_ROOT}/arm64-v8a;${PNG_ROOT}/arm64-v8a;$(pwd)/tools" -DCMAKE_INSTALL_PREFIX="build-target/arm64-v8a/install" \
	-DPSEMEK_BACKEND=ANDROID -DPSEMEK_PACKAGE_MODE=ON -DPSEMEK_PACKAGE_TARGET=ON -DPSEMEK_PACKAGE_TOOLS_PATH="" -DPSEMEK_PACKAGE_HELPER=$(pwd)/package-helper.sh -DPSEMEK_COPY_FILES=$(pwd)/copy-files.sh
cmake --build build-target/arm64-v8a/build -t install -j

mkdir -p app/lib/arm64-v8a
cp -v build-target/arm64-v8a/install/lib/*.so app/lib/arm64-v8a/
cp -v ${NDK_ROOT}/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android/libc++_shared.so app/lib/arm64-v8a/
cp -v ${BOOST_ROOT}/arm64-v8a/lib/*.so app/lib/arm64-v8a/
cp -v ${PNG_ROOT}/arm64-v8a/lib/*.so app/lib/arm64-v8a/

cd app

cp ./AndroidManifest.xml.in ./AndroidManifest.xml
sed -i -e "s/APPLICATION_NAME/$(cat ../application-name)/g" ./AndroidManifest.xml

export TARGET_NAME=$(cat ../target-name)
export APK_NAME=$(cat ../apk-name)

cp src/psemek/app/MainActivity.java.in src/psemek/app/MainActivity.java
sed -i -e "s/TARGET_NAME/${TARGET_NAME}/g" src/psemek/app/MainActivity.java

mkdir -p dex bin

${BUILD_TOOLS_ROOT}/aapt package -f -m -J ./src -M ./AndroidManifest.xml -I ${PLATFORM_ROOT}/android.jar

javac -d obj -classpath src -classpath ${PLATFORM_ROOT}/android.jar src/psemek/app/*.java

${BUILD_TOOLS_ROOT}/d8 --output ./dex obj/psemek/app/*.class

${BUILD_TOOLS_ROOT}/aapt package -f -m -F ./bin/${TARGET_NAME}.unaligned.apk -M ./AndroidManifest.xml -I ${PLATFORM_ROOT}/android.jar
zip -r ./bin/${TARGET_NAME}.unaligned.apk assets
${BUILD_TOOLS_ROOT}/aapt add ./bin/${TARGET_NAME}.unaligned.apk lib/arm64-v8a/*
cd dex
${BUILD_TOOLS_ROOT}/aapt add ../bin/${TARGET_NAME}.unaligned.apk classes.dex
cd ..

${BUILD_TOOLS_ROOT}/zipalign -f 4 ./bin/${TARGET_NAME}.unaligned.apk "${APK_NAME}"

${BUILD_TOOLS_ROOT}/apksigner sign --ks psemek.keystore --ks-pass "pass:${PSEMEK_KEYSTORE_PASSWORD}" "${APK_NAME}"

echo "Packaged target ${TARGET_NAME} into ${APK_NAME}"