#!/bin/bash
#
# script to compile yap for Android.

BUILD=x86_64-apple-darwin

export SDK_ROOT=$HOME/Yap/android-sdk-macosx
export NDK_ROOT=$HOME/Yap/android-ndk-r9d
export NDK_HOST=darwin-x86_64
export GCC_VERSION=4.8
#export PATH=$PATH:"$NDK_ROOT"/toolchains/arm-linux-androideabi-"$GCC_VERSION"/prebuilt/$NDK_HOST/bin
export PATH=$PATH:"$SDK_ROOT"/tools:"$NDK_ROOT"

export GMPDIR=$HOME/Yap/gmp-android

export ANDROID_NDK_ROOT="$NDK_ROOT"/
export ANDROID_SYSROOT="$NDK_ROOT"/platforms/android-17/arch-arm

if test -d $HOME/Yap/my-android-toolchain
then
  echo using the setup at $HOME/Yap/my-android-toolchain
else
  "$NDK_ROOT"/build/tools/make-standalone-toolchain.sh \
                                 --platform=android-17 \
                                 --toolchain=arm-linux-androideabi-"$GCC_VERSION" \
                                 --install-dir="$HOME"/Yap/my-android-toolchain
fi

export PATH=$HOME/Yap/my-android-toolchain/bin:$PATH

cd ~/Yap/bins/android

if test x$1 = xmake
then
  make -j install
  rm -r packages/swig/android
elif test x$1 = xenv
then
  return 0;
elif test x$1 = xeclipse
then
   emulator -avd first &
   ~/eclipse/eclipse &
   exit 0;
# not working
# elif test x$1 = xgmp
# then
#   cd ~/Yap/gmp-6.0.0
#   export LDFLAGS="-Wl,--fix-cortex-a8 -Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now"
#   export BASE_CFLAGS='-O2 -g -pedantic -fomit-frame-pointer -Wa,--noexecstack -ffunction-sections -funwind-tables -fstack-protector -fno-strict-aliasing'
#   export CFLAGS="${BASE_CFLAGS} -mfloat-abi=softfp -mfpu=vfp"
#   export LIBGMP_LDFLAGS='-avoid-version'
#   export LIBGMPXX_LDFLAGS='-avoid-version'
#   export PATH="$NDK_ROOT"/toolchains/arm-linux-androideabi-4.8/prebuilt/$NDK_HOST/arm-linux-androideabi/bin:$PATH
#   export MPN_PATH="arm/v6t2 arm/v6 arm/v5 arm generic"
#   ./configure --host=arm-linux-androideabi  --build=$BUILD --prefix=$HOME/Yap/gmp-android
# #  make
#   exit 0
else
  rm -rf ~/Yap/bins/android/*
  ~/git/yap-6.3/configure --host=arm-linux-androideabi --prefix=`pwd` --with-readline=no --enable-low-level-tracer --enable-debug-yap --enable-dynamic-loading --with-swig --with-gmp=$GMPDIR  --disable-chr #--enable-threads
  make depend
  make -j install

fi
cp libYap.so libYapi.so $GMPDIR/lib/libgmp.so $ANDROID_NDK_ROOT/build/core/lib/
cd packages/swig
mkdir -p $ANDROID_NDK_ROOT/build/core/lib
make android
adb uninstall org.swig.simple
adb install android/bin/SwigSimple-debug.apk