#!/bin/bash
set -eu


# Dependencies
# - MPI implementation (for parallel I/O support)
# - hdf5 (1.8.9 / 1.10.1 or later, for netCDF-4 support)
# - zlib (1.2.5 or later, for netCDF-4 compression)
# - curl (7.18.0 or later, for DAP remote access client support)
#
# For most ISSM installations, only hdf5 will be necessary
#
# Sources:
# - https://www.unidata.ucar.edu/software/netcdf/documentation/NUG/getting_and_building_netcdf.html#building
#

# NOTE:
# - Certain configuration tests fail if libraries are not supplied explicitly

# Constants
#
VER="4.7.2"

HDF5_ROOT="${ISSM_DIR}/externalpackages/petsc/install"
ZLIB_ROOT="${ISSM_DIR}/externalpackages/petsc/install"

# Environment
#
export CC=mpicc
export CPPFLAGS="-I${ZLIB_ROOT}/include"

export HDF5LIB="${HDF5_ROOT}/lib/libhdf5_hl.a ${HDF5_ROOT}/lib/libhdf5.a"
export ZLIB="${ZLIB_ROOT}/lib/libz.a"

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

# Unpack source
tar -zxvf netcdf-c-$VER.tar.gz

# Cleanup
rm -rf install src
mkdir install src

# Move source to 'src' directory
mv netcdf-c-$VER/* src/
rm -rf netcdf-c-$VER

# Configure
cd src
./configure \
	--prefix="${ISSM_DIR}/externalpackages/netcdf/install" \
	--disable-shared \
	--disable-dependency-tracking \
	--enable-fast-install \
	--disable-doxygen \
	--enable-netcdf4 \
	--disable-dap \
	--disable-examples \
	--disable-filter-testing \
	--disable-dap-remote-tests \
	--enable-parallel-tests

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

# Return to initial directory
cd ..
