#!/bin/bash

##
## WARNING: Do not edit this file from inside conda_mkl because this build
## script is soft linked from the conda directory. Therefore, we try to maintain
## one build script and just set environment variables to trigger the mkl
## build.
##
## To trigger the MKL build:
##     export CONDA_BUILD_MKL=1
#

# Copy the contents from above so we can build
cp -r "$RECIPE_DIR/../" .

# Detect linux vs mac
if [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
  DYNAMIC_EXT="so"
fi
if [ "$(uname -s)" == "Darwin" ]; then
  DYNAMIC_EXT="dylib"
fi

# Check if MKL build
if [ $(basename "${RECIPE_DIR}") == "conda_mkl" ]; then
  echo "BUILDING USING MKL"
  CONDA_BUILD_MKL=1
  MKL_LIBS="mkl_intel_lp64 -lmkl_core -lmkl_intel_thread -liomp5 -ldl -lpthread -lm"
  export CFLAGS="-m64"
else
  MKL_LIBS=""
  CONDA_BUILD_MKL=0
fi

# Make the build directory for CMAKE and patch for metis 5
mkdir build
# Patch for Metis 5
patch -p0 < metis5_idx.patch
cd build

export LDFLAGS="-L$LIBRARY_PATH"

################################################################################

# Create the static libraries
cmake .. \
-DLIB_POSTFIX="" \
-DCMAKE_INSTALL_PREFIX="$PREFIX" \
-DUSE_METIS=1 \
-DMETIS_LIB="$LIBRARY_PATH/libmetis.a" \
-DMETIS_INCLUDE_PATH="$INCLUDE_PATH" \
-DSUITESPARSE_USE_CUSTOM_BLAS_LAPACK_LIBS=${CONDA_BUILD_MKL} \
-DSUITESPARSE_CUSTOM_BLAS_LIB="${MKL_LIBS}"
# Not sure if I need the link above - mkl-rt doesn't contain the .a files.

# I have no idea how to stop the CMake from putting -lrt
# inside the link.txt, so I've had to improvise by sed'ing it out
if [ "$(uname -s)" == "Darwin" ]; then
  sed -i"bak" 's/-lrt//' SuiteSparse/UMFPACK/CMakeFiles/umfpack.dir/link.txt
  sed -i"bak" 's/-lrt//' SuiteSparse/SPQR/CMakeFiles/spqr.dir/link.txt
  sed -i"bak" 's/-lrt//' SuiteSparse/CHOLMOD/CMakeFiles/cholmod.dir/link.txt
fi

make -j$CPU_COUNT
make install

################################################################################

# Create the SHARED libraries
cmake .. \
-DBUILD_SHARED_LIBS=1 \
-DLIB_POSTFIX="" \
-DUSE_METIS=1 \
-DMETIS_LIB="$LIBRARY_PATH/libmetis.${DYNAMIC_EXT}" \
-DMETIS_INCLUDE_PATH="$INCLUDE_PATH" \
-DCMAKE_INSTALL_PREFIX="$PREFIX" \
-DSUITESPARSE_USE_CUSTOM_BLAS_LAPACK_LIBS=${CONDA_BUILD_MKL} \
-DSUITESPARSE_CUSTOM_BLAS_LIB="${MKL_LIBS}"

# I have no idea how to stop the CMake from putting -lrt
# inside the link.txt, so I've had to improvise by sed'ing it out
if [ "$(uname -s)" == "Darwin" ]; then
  sed -i"bak" 's/-lrt//' SuiteSparse/UMFPACK/CMakeFiles/umfpack.dir/link.txt
  sed -i"bak" 's/-lrt//' SuiteSparse/SPQR/CMakeFiles/spqr.dir/link.txt
  sed -i"bak" 's/-lrt//' SuiteSparse/CHOLMOD/CMakeFiles/cholmod.dir/link.txt
fi

make -j$CPU_COUNT
make install
