#!/bin/sh
set -e

if [ $# -ne 2 -a $# -ne 3 ]; then
    echo "" 1>&2
    echo "Usage: $0 NDK_DIR ARCH [API]" 1>&2
    echo "" 1>&2
    echo "  NDK_DIR: path where NDK is installed" 1>&2
    echo "  ARCH: armeabi, armeabi-v7a, arm64, mips, mips64, x86, x86_64" 1>&2
    echo "  API: 1 ... 25" 1>&2
    echo "" 1>&2
    echo "If API is omitted, the minimum possible API for the " 1>&2
    echo "required architecture is used." 1>&2
    echo "" 1>&2
    echo "Example usage (on MacOS with Android Studio installed):" 1>&2
    echo "  $0 ~/Library/Android/sdk/ndk-bundle arm 19" 1>&2
    echo "" 1>&2
    exit 1
fi

ROOTDIR=$(cd $(dirname $0) && pwd -P)

NDK_DIR=$1
ARCH=$2
API=$3
BASEDIR=$ROOTDIR/toolchain

# Directory where to install the toolchain. This must be done _before_
# mapping the input architecture to a real toolchain architecture.
INSTALL_DIR=$BASEDIR/${ARCH}

# Map input architecture to toolchain architecture (armeabi and
# armeabi-v7a both use the arm toolchain)
if [ "$ARCH" = "armeabi" -o "$ARCH" = "armeabi-v7a" ]; then
    ARCH="arm"
fi

if [ "$API" = "" ]; then
    if [ "$ARCH" = "arm64" -o "$ARCH" = "mips64" -o "$ARCH" = "x86_64" ]; then
        API=21
    else
        API=14
    fi
fi

MAKE_TOOLCHAIN=${NDK_DIR}/build/tools/make_standalone_toolchain.py

echo "Creating toolchain for API ${API} and ARCH ${ARCH} in ${INSTALL_DIR}"

$MAKE_TOOLCHAIN --arch=${ARCH} --api=${API} --install-dir=${INSTALL_DIR}   \
    --stl=libc++
