#!/bin/bash
set -eu


## Constants
#
VER="6.0.0"

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
#
# Should retrieve a copy of gfortran that is compiled from source before returning one that is installed via package manager
#
# TODO:
# - Test if -static-libgfortran flag will avoid all of this.
# - Otherwise, refactor this to work with other gfortran installations.
#
LIBGFORTRAN=$(mdfind -onlyin /usr -name libgfortran | grep -n libgfortran.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)
LIBGFORTRAN_ROOT=${LIBGFORTRAN%/*}
LIBGCC=$(mdfind -onlyin ${LIBGFORTRAN_ROOT} -name libgcc | grep -n libgcc.a | grep -v i386 | sed "s/[0-9]*://g" | head -1)

GDAL_EXTRA_LIBS="-lc++" # `$GDAL_ROOT/bin/gdal-config --dep-libs` does not report need to link to libc++ (see also customized configuration file ./configs/6.0/static/cmake/modules/FindGDAL.cmake)
NETCDF_EXTRA_LIBS="-lsqlite3 -lpthread -ldl -liconv" # `$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

# 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

# Configure
cd src
mkdir build
cd build

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
