#!/bin/bash
set -eu


## Constants
#
VER="6.0.0"

CURL_ROOT="${ISSM_DIR}/externalpackages/curl/install"
PETSC_ROOT="${ISSM_DIR}/externalpackages/petsc/install"

BLASLAPACK_ROOT="${PETSC_ROOT}"
HDF5_ROOT="${PETSC_ROOT}"

# Find libgfortran and libgcc so we do not have to hardcode them
#
# NOTE: For now, paths are hardcoded.
#
# TODO:
# - Figure out how to find and grep for single result like we do with mdfind 
#	under macOS.
#
LIBGFORTRAN="/usr/lib/gcc/x86_64-linux-gnu/8/libgfortran.a"
LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
LIBGCC="/usr/lib/gcc/x86_64-linux-gnu/8/libgcc.a"

CURL_INCLUDE_DIRS="${CURL_ROOT}/include" \
CURL_LIBRARIES="${CURL_ROOT}/lib/libcurl.a;/usr/lib/x86_64-linux-gnu/libssl.a;/usr/lib/x86_64-linux-gnu/libcrypto.a" \
GDAL_EXTRA_LIBS="-lstdc++" # Determined by running `$GDAL_ROOT/bin/gdal-config --dep-libs` then removing duplicate libs
NETCDF_EXTRA_LIBS="-lm -ldl -lz" # `$NETCDF_ROOT/bin/nc-config --libs` does not report certain dependencies of certain static libraries (see also customized configuration file ./configs/6.0/static/cmake/modules/FindNETCDF.cmake)

# Environment
#
export CC=mpicc
export CURL_INCLUDE_DIRS=${CURL_INCLUDE_DIRS}
export CURL_LIBRARIES=${CURL_LIBRARIES}

# Download source
$ISSM_DIR/scripts/DownloadExternalPackage.sh "https://issm.ess.uci.edu/files/externalpackages/gmt-${VER}.tar.gz" "gmt-${VER}.tar.gz"

# Unpack source
tar -zxvf gmt-${VER}.tar.gz

# Cleanup
rm -rf install src
mkdir install src

# Move source to 'src' directory
mv gmt-${VER}/* src
rm -rf gmt-${VER}

# Copy custom configuration files
cp ./configs/6/static/cmake/ConfigUser.static.cmake ./src/cmake/ConfigUser.cmake
cp ./configs/6/static/cmake/modules/FindGDAL.cmake ./src/cmake/modules
cp ./configs/6/static/cmake/modules/FindGSHHG.cmake ./src/cmake/modules
cp ./configs/6/static/cmake/modules/FindNETCDF.cmake ./src/cmake/modules
cp ./configs/6/static/src/CMakeLists.txt ./src/src

# Configure
cd src
mkdir build
cd build

# NOTE:
# - The CMake modules used to find and probe the BLAS and LAPACK libraries do
#	not seem to handle the situation where BLAS_LIBRARY and LAPACK_LIBRARY are
#	set but we are working with static libraries
#	(see customized ConfigUser.static.cmake). Using BLAS_LIBRARIES and
#	LAPACK_LIBRARIES is a workaround.
#
cmake \
	-DBLAS_LIBRARIES="${BLASLAPACK_ROOT}/lib/libfblas.a;${LIBGFORTRAN_ROOT}/libgfortran.a;${LIBGFORTRAN_ROOT}/libquadmath.a;${LIBGCC}" \
	-DGDAL_EXTRA_LIBS="${GDAL_EXTRA_LIBS}" \
	-DHDF5_ROOT="${HDF5_ROOT}" \
	-DLAPACK_LIBRARIES="${BLASLAPACK_ROOT}/lib/libflapack.a;${LIBGFORTRAN_ROOT}/libgfortran.a;${LIBGFORTRAN_ROOT}/libquadmath.a;${LIBGCC}" \
	-DNETCDF_EXTRA_LIBS="${NETCDF_EXTRA_LIBS}" \
	..

# Compile and install
if [ $# -eq 0 ]; then
	make
	make install
else
	make -j $1
	make -j $1 install
fi
