#!/bin/sh

export ANDROID_HOME="/mnt/c/Users/jacob/AppData/Local/Android/Sdk"
export TOOL_PREFIX="$ANDROID_HOME/build-tools/35.0.1"

# Only really works on Linux, for aarch64.

mkdir -p ../target/apk_build/lib/arm64-v8a
mkdir -p ../target/apk_build/res/values
mkdir -p ../target/apk_build/res/mipmap-hdpi
mkdir -p ../target/apk_build/res/mipmap-mdpi
mkdir -p ../target/apk_build/res/mipmap-xhdpi
mkdir -p ../target/apk_build/res/mipmap-xxhdpi

# Copy the shared library.
cp ../target/aarch64-linux-android/release/libdsa_rs.so ../target/apk_build/lib/arm64-v8a/

# Copy the manifest.
cp AndroidManifest.xml ../target/apk_build/AndroidManifest.xml

cat << EOF > ../target/apk_build/res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">DSA Emulator</string>
</resources>
EOF

pushd ../target/apk_build

$TOOL_PREFIX/aapt2 compile --dir res -o compiled_resources.zip
$TOOL_PREFIX/aapt2 link -o unaligned.apk \
    -I "$ANDROID_HOME/platforms/android-35/android.jar" \
    --manifest AndroidManifest.xml \
    compiled_resources.zip

zip -r unaligned.apk lib/

$TOOL_PREFIX/zipalign -v 4 unaligned.apk aligned.apk

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000 -storepass android -keypass android -dname "CN=Android Debug,O=Android,C=US"

$TOOL_PREFIX/apksigner sign --ks debug.keystore --ks-key-alias androiddebugkey --ks-pass pass:android --key-pass pass:android --out dsa_emulator.apk aligned.apk

cp dsa_emulator.apk ../dsa_emulator.apk

popd
