#!/bin/bash
set -u # NOTE: Do not set -e as it will cause this script to fail when there are errors in underlying Python scripts


## Constants
#
VER="3.12.3"

PETSC_DIR="${ISSM_DIR}/externalpackages/petsc/src" # DO NOT CHANGE THIS
PREFIX="${ISSM_DIR}/externalpackages/petsc/install" # Set to location where external package should be installed

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

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

# Cleanup
rm -rf ${PREFIX} ${PETSC_DIR}
mkdir ${PETSC_DIR}

# Move source to $PETSC_DIR
mv petsc-${VER}/* ${PETSC_DIR}
rm -rf petsc-${VER}

# Configure
#
# - Added -fallow-argument-mismatch option to FFLAGS in order to clear "Error: 
#	Rank mismatch between actual argument at [...]"
# - Added -fallow-invalid-boz option to FFLAGS in order to clear "Error: BOZ 
#	literal constant at [...]"
#
cd ${PETSC_DIR}
./config/configure.py \
	--prefix="${PREFIX}" \
	--PETSC_DIR="${PETSC_DIR}" \
	--FFLAGS="-fallow-argument-mismatch -fallow-invalid-boz" \
	--with-debugging=0 \
	--with-valgrind=0 \
	--with-x=0 \
	--with-ssl=0 \
	--with-pic=1 \
	--with-mpiexec="/c/PROGRA~1/MICROS~1/Bin/mpiexec.exe" \
	--with-mpi-lib="-L${MSMPI_ROOT}/lib -lmsmpi" \
	--with-mpi-include="${MSMPI_ROOT}/include" \
	--with-metis-dir=${METIS_ROOT} \
	--with-parmetis-dir=${PARMETIS_ROOT} \
	--with-blas-lib="-L${BLAS_ROOT}/lib -lblas" \
	--known-64-bit-blas-indices=0 \
	--with-lapack-lib="-L${LAPACK_ROOT}/lib -llapack" \
	--with-scalapack-dir=${SCALAPACK_ROOT} \
	--with-mumps-dir=${MUMPS_ROOT}

# Compile and install
make
make install

# NOTE:
# - Hack to recover from failed installation (appears to happen only on Windows 
#	when reproducing symbolic links in destination directory) rather than 
#	trying to patch src/config/install.py
#
if [ $? -ne 0 ]; then
	make install
fi
