#!/bin/bash

libVer=3.3.1

echo libVer=$libVer

scriptDir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
originalPath=$scriptDir/original
buildPath=$scriptDir/build
installPath=$scriptDir/install

libFilePath=$originalPath/mpich-$libVer.tar.gz
libBuildPath=$buildPath/$libVer
libInstallPath=$installPath/$libVer
libSrcPath=$buildPath/mpich-$libVer

echo
echo libFilePath=$libFilePath
echo libBuildPath=$libBuildPath
echo libInstallPath=$libInstallPath
echo libSrcPath=$libSrcPath
echo

rm -rf $buildPath $installPath

mkdir -p $libBuildPath
mkdir -p $libInstallPath
mkdir -p $libSrcPath

tar zxvpf $libFilePath -C $buildPath

if [ -z "$1" ]; then
  BuildType="release"
else
  BuildType="$1"
fi

echo
echo "BuildType      = $BuildType"
echo

# check on 1st argument: build type
if [ "$BuildType" = "debug" ]; then
  echo "debug build selected ..."
  BCFLAGS=-g
  BCXXFLAGS=-g
  BFFLAGS=-g
elif [ "$BuildType" = "release" ]; then
  echo "release build selected ..."
  BCFLAGS=-O3
  BCXXFLAGS=-O3
  BFFLAGS=-O3
else
  echo "Error: unrecognized build type. Check 1st input argument!"
  exit
fi

echo
echo "BCFLAGS         = $BCFLAGS"
echo "BCXXFLAGS       = $BCXXFLAGS"
echo "BFFLAGS         = $BFFLAGS"
echo

# print current LD_LIBRARY_PATH for reference
echo "LD_LIBRARY_PATH = $LD_LIBRARY_PATH"

# run the configure command with all build options
(cd $libBuildPath &&
  $libSrcPath/configure \
    --prefix=$libInstallPath \
    --disable-fc \
    --disable-f77 \
    --disable-fortran \
    --disable-cxx \
    --enable-fast=all \
    MPICHLIB_CFLAGS=$BCFLAGS \
    CC=gcc \
    CXX=g++ \
    2>&1 | tee config.out.txt)

# clean, build, and install
(cd $libBuildPath &&
  make clean)

(cd $libBuildPath &&
  make install -j 2>&1 | tee build.out.txt)
