#!/bin/bash

set -ex

# Setup CMake build location
mkdir build
cd build

# Configure, build, test, and install.
if [ "$(uname)" == "Linux" ];
then
    # Stop Boost from using libquadmath.
    export CXXFLAGS="${CXXFLAGS} -DBOOST_MATH_DISABLE_FLOAT128"
fi

if [[ ${NOMKL} == 1 ]]; then
    BLAS=open
else
    BLAS=mkl
fi

cmake \
      -DUSE_CUDNN=1                                         \
      -DCUDA_ARCH_NAME="Manual"                             \
      -DCUDA_ARCH_BIN="20 21(20) 30 35 50 52"               \
      -DNUMPY_INCLUDE_DIR="${SITE_PKGS}/numpy/core/include" \
      -DCMAKE_INSTALL_PREFIX="${PREFIX}"                    \
      -DPYTHON_EXECUTABLE="${PREFIX}/bin/python"            \
      -DBLAS="${BLAS}"                                      \
      ..
make -j${CPU_COUNT}
LD_LIBRARY_PATH=/usr/local/nvidia/lib:/usr/local/nvidia/lib64:${LD_LIBRARY_PATH} make -j${CPU_COUNT} runtest
make install

# Python installation is non-standard. So, we're fixing it.
mv "${PREFIX}/python/caffe" "${SP_DIR}/"
for FILENAME in $( cd "${PREFIX}/python/" && find . -name "*.py" | sed 's|./||' );
do
    chmod +x "${PREFIX}/python/${FILENAME}"
    cp "${PREFIX}/python/${FILENAME}" "${PREFIX}/bin/${FILENAME//.py}"
done
rm -rf "${PREFIX}/python/"
