#!/bin/bash -e
#
# 2014/01/06 gabriel

exists_np=''
exists_mf=''
exists_vb=''

for opt in $*
do
   [ "${opt}" == "-np" ]           && exists_np='y'
   [ "${opt}" == "-machinefile" ]  && exists_mf='y'
   [ "${opt}" == "--machinefile" ] && exists_mf='y'
   [ "${opt}" == "-hostfile" ]     && exists_mf='y'
   [ "${opt}" == "--hostfile" ]    && exists_mf='y'
   [ "${opt}" == "--host" ]        && exists_mf='y'
   [ "${opt}" == "-host" ]         && exists_mf='y'
   [ "${opt}" == "-H" ]            && exists_mf='y'
   [ "${opt}" == "--verbose" ]     && exists_vb='y'
   [ "${opt}" == "-v" ]            && exists_vb='y'
   [ "${opt}" == "--" ]            && break
done

[ -n "${VERBOSE:+x}" ] && exists_vb='y'

mpi_option=''

# NODEFILE to use. By default specialized one
nodefile="${OAR_NODE_FILE}"
[ -n "${OAR_MSG_NODEFILE:+x}" -a -e "${OAR_MSG_NODEFILE}" ] && nodefile="${OAR_MSG_NODEFILE}"
if [ -z ${exists_mf} ]
then
   [ -e "${nodefile}" ] && mpi_option="-machinefile ${nodefile} ${mpi_option}"
fi

# Number of MPI parallel run. By default MAX.
nbcpus=''
[ -e "${nodefile}" ]  && nbcpus=$(cat ${nodefile} | wc -l)
[ -n "${OAR_NP:+x}" ] && nbcpus=${OAR_NP}
if [ -z ${exists_np} ]
then
   [ -z ${nbcpus} ] || mpi_option="-np ${nbcpus} ${mpi_option}"
fi

# Change login remote shell
if [ "${OMPI_MCA_plm_rsh_agent}" == "oarsh" ]
then
   OMPI_MCA_plm_rsh_agent="oar-envsh"
fi

[ ! -z ${exists_vb} ] && echo mpirun ${mpi_option} $*
exec mpirun ${mpi_option} $*
