#!/bin/bash
#
# Copyright 2022 Skycloud Software
#
# This script is a wrapper for Open MPI mpirun
# it generates the machine file based on the hosts
# given to it by AIP.
# 
# In case of using Singularity, set environment of
# CB_SINGULARITY_IMAGE and CB_SINGULARITY_OPTIONS
if echo $LSF_ENVDIR | grep -q lsf; then
    CB_JOBFILENAME=$LSB_JOBFILENAME
    CB_JOBID=$LSB_JOBID
    CB_DJOB_NUMPROC=$LSB_DJOB_NUMPROC
    RSH=blaunch
else
    RSH=rsh
fi

if [ x"${CB_JOBFILENAME}" = x -o x"${LSB_MCPU_HOSTS}" = x ]; then
    mpirun $*
    exit $?
fi

MYARGS=$*
WORKDIR=`dirname ${CB_JOBFILENAME}`
rm -f ${WORKDIR}/mpi_machines.*
MACHFILE=${WORKDIR}/mpi_machines.${CB_JOBID}

T=`echo "${MYARGS}" | grep -- -machinefile |wc -l`
if [ $T -gt 0 ]; then
    echo "Error:  Do not provide the machinefile for mpirun."
    echo "        It is generated automatically for you."
    exit -3
fi

# Make the Open MPI machine file
hostlist -o > ${MACHFILE}
if [ $? != 0 ]; then
    echo "OpenMP is used. The CPU requirement is incorrect"
    exit 1
fi

if [ _$OMP_NUM_THREADS != '_' ]; then
    CB_DJOB_NUMPROC=$((CB_DJOB_NUMPROC/OMP_NUM_THREADS))
fi

if [ _$CB_SINGULARITY_IMAGE == '_' ]; then
    mpirun=mpirun
else
    CB_SINGULARITY_OPTIONS="--pid "$CB_SINGULARITY_OPTIONS
    mpirun="singularity exec $CB_SINGULARITY_OPTIONS $CB_SINGULARITY_IMAGE `which mpirun` -x PATH"
fi

exec $mpirun -x LD_LIBRARY_PATH -np $CB_DJOB_NUMPROC \
-machinefile ${MACHFILE} --mca plm_rsh_agent `which $RSH` \
-x LSB_MCPU_HOSTS \
--mca fwd_mpirun_port 16001 ${MYARGS}
