#!/bin/bash
set -e -x -u


OSNAME=android
abi_name=x86
target_dir=''
if [[ -n ${_BUILD_CFG-} ]]; then
    IFS=' ' read -r abi_name target_dir <<< ${_BUILD_CFG}
fi

if [[ -z "${target_dir}" ]]; then
    target_dir=out/$OSNAME/Release
fi

if [[ -z ${NDK_ROOT+x} ]]; then
    if [[ $OSTYPE == 'darwin'* ]]; then
        NDK_ROOT=`ls -Ad $HOME/Library/Android/sdk/ndk/* 2>/dev/null | tail -1`
    else
        NDK_ROOT=`ls -Ad $HOME/Android/Sdk/ndk/* 2>/dev/null | tail -1`
    fi
fi
if [[ -z "${NDK_ROOT}" ]]; then
    echo "ERROR: cannot find where NDK was installed, using NDK_ROOT to specify it"
    exit 7
fi
if [[ -z ${ANDROID_SDK_ROOT+x} ]]; then
    export ANDROID_SDK_ROOT=$(dirname $(dirname  ${NDK_ROOT}))
fi
if [[ -z ${ANDROID_NDK_VERSION+x} ]]; then
    CURRENT_NDK_VERSION=$(basename ${NDK_ROOT})
else
    CURRENT_NDK_VERSION=${ANDROID_NDK_VERSION}
fi

mkdir -p ${target_dir}
pushd ${target_dir}
# ANDROID_PLATFORM, the minimum level is 24, i.e., due to
#       the great change of file system permission in Android 7
cmake "$@" \
    -DCMAKE_TOOLCHAIN_FILE=${NDK_ROOT}/build/cmake/android.toolchain.cmake  \
    -DANDROID_NDK=${NDK_ROOT}                                               \
    -DANDROID_ABI=${abi_name}                                               \
    -DANDROID_PLATFORM=android-24                                           \
    -DOCOS_BUILD_ANDROID=ON                                                 \
    -DANDROID_NDK_VERSION=${CURRENT_NDK_VERSION}                            \
    ../../.. && cmake --build . --config Release --parallel
popd
