#!/bin/bash
#
# Copyright 2022 Skycloud Software 
#
# This script is a wrapper for Intel MPI, MPICH,
# and MVAPICH in a large environment where the default
# Hydra fails to get AIP allocated slots
#
# This script supports running the job in Apptainer.
#

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 IMPI machine file
hostlist -m > ${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 --env PATH=$PATH "$CB_SINGULARITY_OPTIONS
    mpirun="singularity exec $CB_SINGULARITY_OPTIONS $CB_SINGULARITY_IMAGE `which mpirun`"
fi

exec mpirun -machinefile ${MACHFILE} -np ${CB_DJOB_NUMPROC} \
-launcher rsh ${MYARGS}
