#!/bin/bash
#Step 1: unzip and install
#Step 2: After MUMPS Crashes
STEP=0

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

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

	#configure
	cd install
	./config/configure.py  \
		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
		--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
		--PETSC_ARCH=macosx-gnu \
		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
		--with-fc=/usr/local/bin/gfortran \
		--with-debugging=0 \
		--with-shared=0 \
		--download-mumps=yes \
		--download-scalapack=yes \
		--download-blacs=yes \
		--download-blas=yes \
		--download-f-blas-lapack=yes \
		--FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -L$ISSM_DIR/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran  -fPIC -arch i386" \
		--download-plapack=yes \
		--CXXFLAGS=" -fPIC -arch i386" \
		--CFLAGS=" -fPIC -arch i386" \
		--with-pic \
		--with-fc="gfortran -arch i386 " \
		--LDFLAGS="-arch i386"
	echo "== Fix MUMPS compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
	echo "== Then run STEP=2 =="
fi

if [ $STEP -eq 2 ]; then
	cd install
	./config/configure.py  \
		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
		--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
		--PETSC_ARCH=macosx-gnu \
		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
		--with-fc=/usr/local/bin/gfortran \
		--with-debugging=0 \
		--with-shared=0 \
		--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/MUMPS_4.6.3  \
		--download-scalapack=yes \
		--download-blacs=yes \
		--download-blas=yes \
		--download-f-blas-lapack=yes \
		--FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -L$ISSM_DIR/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran  -fPIC -arch i386" \
		--download-plapack=yes \
		--CXXFLAGS=" -fPIC -arch i386" \
		--CFLAGS=" -fPIC -arch i386" \
		--with-pic \
		--with-fc="gfortran -arch i386 " \
		--LDFLAGS="-arch i386"

	#Compile petsc and install it
	make
	make install
fi
