#!/bin/bash

  # Retrieve script variables
  targetDir=$1
  if [ "$#" -gt 1 ]; then
    tryEnableMPIMerge=$2
  else
    tryEnableMPIMerge=false
  fi

  scriptDir=$(pwd)/$(dirname $0)

  # Setup Extrae for PAPI (or not) 
  papiPath=$(which papi_avail 2> /dev/null)
  if [ -z ${papiPath} ]; then
    # No PAPI available
    papiArg="--without-papi"
  else
    # PAPI available
    papiBaseDir=${papiPath%/bin**}
    papiArg="--with-papi=${papiBaseDir}"
  fi

  # Setup MPI for parallel merge (or not)
  mpiPath=$(which mpirun 2> /dev/null)
  if ! $tryEnableMPIMerge || [ -z ${mpiPath} ]; then
    # No MPI available
    mpiArg="--without-mpi"
  else
    # MPI available detect openmpi or impi
    if [ -z "$I_MPI_ROOT" ]; then
        mpiBaseDir=${mpiPath%/bin**}
    else
        mpiBaseDir=${I_MPI_ROOT}
    fi

    mpiArg="--with-mpi=${mpiBaseDir} --enable-parallel-merge"
  fi

  # Create installation folder
  mkdir -p ${targetDir}

  # Configure, compile and install
  autoreconf --force --install
  if [ $? -ne 0 ]; then
    exit 1
  fi

  ./configure --enable-gettimeofday-clock \
              --without-unwind \
              --without-dyninst \
              --without-binutils \
              ${mpiArg} \
              ${papiArg} \
              --with-java-jdk=${JAVA_HOME} \
              --disable-openmp \
              --disable-nanos \
              --disable-smpss \
              --enable-instrument-io \
              --prefix=${targetDir} \
              --libdir=${targetDir}/lib
  if [ $? -ne 0 ]; then
    exit 1
  fi

  make clean install
  if [ $? -ne 0 ]; then
    exit 1
  fi  

  # Exit normal
  exit 0

