#!/bin/bash

# From http://www.hanshq.net/command-line-android.html
#
# Note: this expects $JAVA_HOME to be set and the JDK tools to be in $PATH.

set -xeu

SDK="$HOME/android_sdk"
NDK="$SDK/ndk/26.2.11394342"

BUILD_TOOLS="$SDK/build-tools/34.0.0"
PLATFORM="$SDK/platforms/android-34"

ARM_CLANG="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi33-clang"
ARM64_CLANG="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang"
X86_CLANG="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android33-clang"

mkdir -p build/gen build/obj build/apk
mkdir -p build/apk/lib/armeabi-v7a build/apk/lib/arm64-v8a \
    build/apk/lib/x86_64

"$BUILD_TOOLS/aapt" package -f -m -J build/gen/ -S res \
    -M AndroidManifest.xml -I "$PLATFORM/android.jar"

javac --release 11 -classpath "$PLATFORM/android.jar" -d build/obj \
    build/gen/net/hanshq/hello/R.java java/net/hanshq/hello/MainActivity.java

"$BUILD_TOOLS/d8" --release --lib "$PLATFORM/android.jar" \
      --output build/apk/ build/obj/net/hanshq/hello/*.class

"$ARM_CLANG" -fpic -shared -o build/apk/lib/armeabi-v7a/libhello.so \
    jni/hello.c
"$ARM64_CLANG" -fpic -shared -o build/apk/lib/arm64-v8a/libhello.so \
    jni/hello.c
"$X86_CLANG" -fPIC -shared -o build/apk/lib/x86_64/libhello.so \
    jni/hello.c

"$BUILD_TOOLS/aapt" package -f -M AndroidManifest.xml -S res/ \
    -I "$PLATFORM/android.jar" \
    -F build/Hello.unsigned.apk build/apk/

"$BUILD_TOOLS/zipalign" -f -p 4 \
    build/Hello.unsigned.apk build/Hello.aligned.apk

# keytool -genkeypair -keystore keystore.jks -alias androidkey \
#     -validity 10000 -keyalg RSA -keysize 2048 \
#     -storepass android -keypass android

"$BUILD_TOOLS/apksigner" sign --ks keystore.jks \
    --ks-key-alias androidkey --ks-pass pass:android \
    --key-pass pass:android --out build/Hello.apk \
    build/Hello.aligned.apk
