#!/bin/bash

ARCH=$1
cwd=$(realpath $0)
ANDROID_NDK=${2%/}
PYTHON_PATH=${3%/}

throw_error () {
  echo $1
  exit 1
}

NDK_PROP_PATH="$ANDROID_NDK/source.properties"
if [ -f $NDK_PROP_PATH ]
then
  version=$(cat $NDK_PROP_PATH | grep -oP '[0-9]+(?=[.])' | head -1)
  if [ $version != "19" ]
  then
    throw_error "This script assumes NDK r19, exiting..."
  fi
else
  throw_error "ERROR: incorret NDK path"
fi

# determine android target machine
if [ $ARCH == "x86" ]
then
  ANDROID_TARGET="i686-linux-android"
elif [ $ARCH == "x86_64" ]
then
  ANDROID_TARGET="x86_64-linux-android"
elif [ $ARCH == "arm" ]
then
  ANDROID_TARGET="armv7a-linux-androideabi"
  BIN_UTILS_PREFIX="arm-linux-androideabi"
elif [ $ARCH == "arm64" ]
then
  ANDROID_TARGET="aarch64-linux-android"
else
  throw_error "ERROR: specify correct architecture (x86, x86_64, arm, arm64)"
fi

# determine android API level
if [ -z "${ARCH##*64*}" ]
then
  ANDROID_API="21"
else
  ANDROID_API="16"
fi

# set prefix for binary utilities
if [ -z "$BIN_UTILS_PREFIX" ]
then
  BIN_UTILS_PREFIX=$ANDROID_TARGET
fi

cd $PYTHON_PATH

# set the $PATH environment variable
export PATH="$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH"

# set environment variables for compilers
export CC="${ANDROID_TARGET}${ANDROID_API}-clang"
export CXX="$CC++"

# set environment variables for binary utils..
export AR="$BIN_UTILS_PREFIX-ar"
export LD="$BIN_UTILS_PREFIX-ld"
export AS="$BIN_UTILS_PREFIX-as"
export STRIP="$BIN_UTILS_PREFIX-strip"
export RANLIB="$BIN_UTILS_PREFIX-ranlib"
export READELF="$BIN_UTILS_PREFIX-readelf"

# set compiler and linker flags appropriately
export CFLAGS="-fPIE -fPIC"
export LDFLAGS="-fuse-ld=lld -Wl,--rpath=../lib"

export CONFIG_SITE="config.site"

CONFIG_BUILD="$(uname -m)-linux-gnu"
CONFIG_ARGS="--enable-shared --disable-ipv6"
CONFIG_PREFIX="$PYTHON_PATH/output/$ARCH-android"

echo "Building for target machine..."
sleep 2
$PYTHON_PATH/configure --host=$ANDROID_TARGET --build=$CONFIG_BUILD --prefix=$CONFIG_PREFIX $CONFIG_ARGS
make -C $PYTHON_PATH $MAKE_ARGS
make -C $PYTHON_PATH install

echo ""
echo "-----"
echo "DONE!"
echo "Build output directory -> $CONFIG_PREFIX"
