#!/bin/bash
set -eu
#Step 1: unzip and install
#Step 2: After Plapack implodes
STEP=0

if [ $STEP -eq 1 ]; then
	#Some cleanup
	rm -rf install petsc-3.1-p7 src
	mkdir install src

	#Download from ISSM server
	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'

	#Untar and move petsc to install directory
	tar -zxvf  petsc-3.1-p7.tar.gz
	mv petsc-3.1-p7/* install/
	rm -rf petsc-3.1-p7

	#configure
	cd src
	./config/configure.py \
	  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
	  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
	  --ISSM_ARCH=$ISSM_ARCH \
	  --with-debugging=no \
	  --with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
	  --with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
	  --with-mpi-lib=/usr/lib/libmpi.so \
	  --with-mpi-include=/usr/include  \
	  --with-mpi-shared=0 \
	  --download-mumps=yes \
	  --download-scalapack=yes \
	  --download-blacs=yes  \
	  --download-plapack=yes \
	  --FFLAGS=-I/usr/include \
	  --with-cc=icc \
	  --with-fc=ifort  \
	  --download-parmetis=yes

	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc31/) =="
	echo "== Then run STEP=2 =="
fi
if [ $STEP -eq 2 ]; then
	cd src
	./config/configure.py \
		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
		--with-batch=1  \
		--ISSM_ARCH=$ISSM_ARCH \
		--with-debugging=no \
		--with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
		--with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
		--with-mpi-lib=/usr/lib/libmpi.so \
		--with-mpi-include=/usr/include  \
		--with-mpi-shared=0 \
		--download-mumps=yes \
		--download-scalapack=yes \
		--download-blacs=yes  \
		--with-plapack-dir=$PETSC_DIR/externalpackages/PLAPACKR32-hg/$ISSM_ARCH \
		--FFLAGS=-I/usr/include \
		--with-cc=icc \
		--with-fc=ifort  \
		--download-parmetis=yes
	echo "== Follow PETSc's instructions"
fi
