#!/bin/bash

##################
# Load mpicc and mpicxx into $PATH
##################

#. /usr/share/[mM]odules/init/bash
#module load mvapich2-gnu-psm/1.7

. /usr/local/tools/dotkit/init.sh
use mvapich2-gnu-2.2

# MVAPICH
#curdir=`pwd`
#export PATH="${curdir}/mvapich2/install/bin:$PATH"

# Open MPI
#curdir=`pwd`
#export PATH="${curdir}/openmpi/install/bin:$PATH"

##################
# Build software
##################

set -x

OPT="-g -O0"

installdir=`pwd`/install

# if EA is set to true then add configure option
EA=false
build_type=""
if $EA ; then
        # build line option required if building for EA systems
        build_type="powerpc64le-redhat-linux-gnu"
fi
 
mkdir -p deps
cd deps

# specify versions of software
# (may need to update some other lines further below)
libcircle=libcircle-0.2.1-rc.1
lwgrp=lwgrp-1.0.2
dtcmp=dtcmp-1.0.3
libarchive=libarchive-3.1.2

# fetch dependencies
if [ ! -f ${libcircle}.tar.gz ] ; then
  wget https://github.com/adammoody/libcircle/releases/download/v0.2.1-rc.1/${libcircle}.tar.gz
fi
if [ ! -f ${lwgrp}.tar.gz ] ; then
  wget https://github.com/hpc/lwgrp/releases/download/v1.0.2/${lwgrp}.tar.gz
fi
if [ ! -f ${dtcmp}.tar.gz ] ; then
  wget https://github.com/hpc/dtcmp/releases/download/v1.0.3/${dtcmp}.tar.gz
fi
if [ ! -f ${libarchive}.tar.gz ] ; then 
  wget http://www.libarchive.org/downloads/${libarchive}.tar.gz
fi

# build dependencies
rm -rf ${libcircle}
tar -zxf ${libcircle}.tar.gz
pushd ${libcircle}
  export CFLAGS=${OPT}
  ./configure --build=${build_type} \
    --prefix=$installdir \
    --disable-silent-rules && \
  make VERBOSE=1 && \
  make VERBOSE=1 install
  if [ $? -ne 0 ]; then
    echo "failed to configure, build, or install libcircle"
    exit 1
  fi
popd

rm -rf ${lwgrp}
tar -zxf ${lwgrp}.tar.gz
pushd ${lwgrp}
  export CFLAGS=${OPT}
  ./configure --build=${build_type} \
    --prefix=${installdir} \
    --disable-silent-rules && \
  make && \
  make install
  if [ $? -ne 0 ]; then
    echo "failed to configure, build, or install liblwgrp"
    exit 1
  fi
popd

rm -rf ${dtcmp}
tar -zxf ${dtcmp}.tar.gz
pushd ${dtcmp}
  export CFLAGS=${OPT}
  ./configure --build=${build_type} \
    --prefix=${installdir} \
    --disable-silent-rules \
    --with-lwgrp=${installdir} && \
  make && \
  make install
  if [ $? -ne 0 ]; then
    echo "failed to configure, build, or install libdtcmp"
    exit 1
  fi
popd

rm -rf ${libarchive}
tar zxvf ${libarchive}.tar.gz
pushd ${libarchive}
  export CFLAGS=${OPT}
  ./configure --build=${build_type} \
    --prefix=${installdir} && \
  make && \
  make install
  if [ $? -ne 0 ]; then
    echo "failed to configure, build, or install libarchive"
    exit 1
  fi
popd
