#! /bin/bash

function set_mpi()
{
  if [ x"$MPI_valid" == x"yes" ]; then
        configure_options="$configure_options CXX=mpic++ "
  else
        if [ $call_test_working_mpi_options -eq 1 ]; then
                test_working_mpi_options
        fi
        ./script/install_MPI.sh $1 $2 $3 $4 $5 $6 $7 "$openmpi_working_options"
        MPI_installed=1
        export PATH="$1/MPI/bin:$PATH"
        configure_options="$configure_options CXX=mpic++ "
  fi

}

function is_openmpi_cuda_aware()
{
  output=$(ompi_info --parsable --all | grep mpi_built_with_cuda_support:value)
  cuda_mpi_support=$(echo $output | sed 's/mca:mpi:base:param:mpi_built_with_cuda_support:value:\(.*\)/\1/g')
}

function get_openmpi_compilation_options()
{
	output=$(ompi_info --config | grep "Configure command line:")
	list=$(echo $output | sed 's/Configure command line:\(.*\)/\1/g')
	arr=($list)

	openmpi_compilation_options=()
	for opt in ${arr[@]}; do
		opt_filter=$(echo $opt | sed "s/'\(.*\)'/\1/g" )
		openmpi_compilation_options+=("$opt_filter")
	done
}

function test_working_mpi_options()
{
	script/download_MPI.sh
	cd openmpi-3.1.3
	openmpi_working_options=()
        for opt in ${openmpi_compilation_options[@]}; do
	       # prefix and --with-cuda must be avoided

		if [[ $opt == --with-cuda* ]]; then
			continue;
		fi

                if [[ $opt == --prefix* ]]; then
                        continue;
                fi

		if [[ $opt == --enable-mpi-fortran* ]]; then
			continue;
		fi

                if [[ $opt == CC* ]]; then
                        continue;
                fi

                if [[ $opt == CXX* ]]; then
                        continue;
                fi

                if [[ $opt == FC* ]]; then
                        continue;
                fi

                if [[ $opt == F77* ]]; then
                        continue;
                fi

		echo "Testing ./configure --prefix=$1/MPI --enable-mpi-fortran=yes CC=$4 CXX=$5 F77=$6 FC=$7 $openmpi_working_options"
                ./configure --prefix=$1/MPI --enable-mpi-fortran=yes CC=$4 CXX=$5 F77=$6 FC=$7 $openmpi_working_options $opt

	       if [ $? -eq 0 ]; then
	           openmpi_working_options="$openmpi_working_options $opt"
	       fi
	done

	echo "OpenMPI working options: $openmpi_working_options"

	cd ..
}