#!/bin/bash

libVer=4.0.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/openmpi-$libVer.tar.gz
libBuildPath=$buildPath/$libVer
libInstallPath=$installPath/$libVer
libSrcPath=$buildPath/openmpi-$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"

# deselected options
#--with-fca \
#--with-verbs=yes \
#--with-udapl \
#--enable-sparse-groups \
#--enable-ipv6 \
#--with-threads=posix \
#--enable-mpi-thread-multiple \
#--enable-mca-static=allocator,bml,btl-sm,btl-self,coll,common-sm,errmgr,gpr,io,iof,maffinity-first_use,mpool-sm,ns,odls,oob,osc,pls,pml,ras,rcache,rds,rmaps,rmgr,rml,sds,topo \
#--enable-vt \
#CXXFLAGS=$BCXXFLAGS \
#FCFLAGS=$BFFLAGS

# run the configure command with all build options
(cd $libBuildPath &&
  $libSrcPath/configure \
    --prefix=$libInstallPath \
    --disable-vt \
    --disable-mpi-cxx \
    --disable-static \
    --disable-wrapper-rpath \
    --disable-wrapper-runpath \
    --disable-dlopen \
    --enable-mca-static=allocator,bml,btl-sm,btl-self,coll,common-sm,errmgr,gpr,io,iof,maffinity-first_use,mpool-sm,ns,odls,oob,osc,pls,pml,ras,rcache,rds,rmaps,rmgr,rml,sds,topo \
    CFLAGS=$BCFLAGS \
    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)
