#!/usr/bin/env bash

# mpich included in the package is built without PBS.
# If you want to use PBS with the pipeline, you may
# need to recompile mpich with PBS in your machine.

set -e

pbs_dir="$1"
if [[ -z "$pbs_dir" ]]
then
    echo "$(basename $0)  PBS_DIR"
    echo ""
    echo "Recompile mpich with PBS."
    echo "PBS_DIR/include/tm.h and PBS_DIR/lib/libtorque.so must exist."
    exit 1
fi

if [[ ! -e "$pbs_dir/include/tm.h" || ! -e "$pbs_dir/lib" ]]
then
    echo "$pbs_dir/{include/tm.h,lib} do(es) not exist."
    exit 1
fi

# Make $pbs_dir an absolute path
pushd "$pbs_dir" &> /dev/null
pbs_dir="$PWD"
popd &> /dev/null

# Setup environment variables
. "$(dirname "$0")"/../bashrc
reset-env
. "$(dirname "$0")"/../bashrc
setup-eups
setup mpich

# Get configuration for the product
product=mpich
product_ver=( $(eups list --setup $product) )
product_dir=$(eups path 0)/$(eups flavor)/$product/$product_ver

# Download the source file
curl -L \
    http://www.mpich.org/static/downloads/$product_ver/$product-$product_ver.tar.gz |
tar xzf -

cd $product-$product_ver

# Tell gcc the place of PBS
export CPATH="$pbs_dir/include"
export LIBRARY_PATH="$pbs_dir/lib"

# Run ./configure with the same options as in http://hsca.ipmu.jp/sumire/packages/builds/mpich-3.1.4.build
./configure --prefix=$product_dir --enable-shared --disable-fortran

# mpich cannot be compiled concurrently
make -j 1
make -j 1 install

# end
