#! /bin/sh

#
# PRUN for PLanguages
# 

#
# Default Variables
#
if [ -d "$MPIRUN" -o ! -x "$MPIRUN" ] ; then
  MPIRUN="/usr/local/bin/mpirun"
fi

#
# Check mpirun location
#
if [ -d $MPIRUN -o ! -x "$MPIRUN" ]; then
  MPIRUN=`whereis mpirun | sed -e 's/.*: *//' | sed -e 's/ .*//' `
  if [ -d $MPIRUN -o ! -x "$MPIRUN" ]; then
    echo "Where is mpirun? You may set MPIRUN before running prun"
    exit
  fi
  echo "Using $MPIRUN"
fi 

#
# Get the temp directory
#
if [ -n "$TMPDIR" ] ; then
  TEMPDIR=$TMPDIR
else
  TEMPDIR="/tmp"
fi
export TEMPDIR

#
# generate a temporary file
#
tempmachinefile="$TEMPDIR/plang-${LOGNAME}$$"

#
# Get number of processors and list of machines
#
np=$1
shift
machinefile=$1
shift 

if [ "$np" = "" -o "$machinefile" = "" ] ; then
  echo "prun <number> <file-list> mpiarguments"
  exit
fi

#
# Verify the list of machines
#
if [ -n $machinefile -a -r $machinefile ] ; then
#  cat $machinefile | tr '\012' ' ' | sed -e 's/ \{1,\}/ /g' | sed -e 's/^ //g' | tr ' ' '\012' > ${tempmachinefile}
  cat $machinefile | gawk --source='BEGIN{n=0}{ if ($1) { printf "%s\n", $1 ; n++;}  }' > ${tempmachinefile} 
else
  echo "Wrong machinefile"
  exit
fi

#
# Get program name and the list of arguments
#
while [ 1 -le $# ] ; do 
  arg=$1
  shift
  args="$args $arg"
done

if [ "$args" = "" ] ; then
  echo "prun <number> <machine-list> mpi-arguments"
  exit
fi

#
# Just try to call mpirun 
#
echo "Running ${MPIRUN} -np ${np} -machinefile ${tempmachinefile} ${args}"
eval "${MPIRUN} -np ${np} -machinefile ${tempmachinefile} ${args}"

#
# Delete temporaries
#
rm -f ${tempmachinefile}

