#!/bin/bash

# Based on http://www.hanshq.net/command-line-android.html
#
# This expects $JAVA_HOME to be set and the JDK tools to be in $PATH.
# For example:
# $ export JAVA_HOME="${HOME}/jdk1.8.0_112"
# $ export PATH="${JAVA_HOME}/bin:${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"

rm -rf build
mkdir -p build/gen build/obj
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/reversi/R.java java/net/hanshq/reversi/*.java

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

"$ARM_CLANG" -fpic -shared -o build/apk/lib/armeabi-v7a/libothello.so \
    -Wall -Wextra -O3 -DNDEBUG -std=c99 -pedantic -I.. \
    jni/othello_board.c ../othello.c
"$ARM64_CLANG" -fpic -shared -o build/apk/lib/arm64-v8a/libothello.so \
    -Wall -Wextra -O3 -DNDEBUG -std=c99 -pedantic -I.. \
    jni/othello_board.c ../othello.c
"$X86_CLANG" -fPIC -shared -o build/apk/lib/x86_64/libothello.so \
    -Wall -Wextra -O3 -DNDEBUG -std=c99 -pedantic -I.. \
    jni/othello_board.c ../othello.c

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

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

if [ ! -f keystore.jks ]; then
        keytool -genkeypair -keystore keystore.jks -alias androidkey \
            -validity 10000 -keyalg RSA -keysize 2048 \
            -storepass android -keypass android
fi

if [ "${@-1}" = "release" ]; then
        echo Signing with the upload key.
        "$BUILD_TOOLS/apksigner" sign --ks release_keystore.jks \
            --ks-key-alias uploadkey --out build/Othello.apk \
            build/Othello.aligned.apk
else
        "$BUILD_TOOLS/apksigner" sign --ks keystore.jks \
            --ks-key-alias androidkey --ks-pass pass:android \
            --key-pass pass:android --out build/Othello.apk \
            build/Othello.aligned.apk
fi


# To run:
# $ "$SDK/platform-tools/adb" install -r build/Othello.apk
# $ "$SDK/platform-tools/adb" shell am start -n net.hanshq.reversi/.OthelloActivity
