#!/bin/sh
#
# wrapper for MPI-style argument.
# Final ampirun script is generated by charm configure from ampirun.in.
# Ampirun supports both net and mpi versions of Charm++.
#  Gengbin Zheng 11/6/2005

mfile=""
nodefile=""
charmarch=
nPE=
opts=
verbose=0

# replaced by configure
arch=mpi-win32

# machinefile => nodelist
ConvertMachinefile()
{
  if test ! -f $mfile
  then
    echo "Error: $mfile not found!"
    exit 1
  fi
  nodefile="/tmp/.node.$$"
  test $verbose = 1 && echo "Generating nodelist file: $nodefile"
  echo 'group main ++shell "/usr/bin/ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o CheckHostIP=no -o BatchMode=yes"' > $nodefile
  nodes=`grep -v '^#' $mfile | awk -F: '{ print $1; }'`
  for node in $nodes
  do
    echo "host $node" >> $nodefile
  done
}

CharmArch()
{
if test x$arch = x
then
  echo "Unknown Charm architecture!"
  exit 1
elif `echo $arch | grep 'mpi-' > /dev/null 2>&1`
then
  charmarch="mpi"
elif `echo $arch | grep 'net-' > /dev/null 2>&1`
then
  charmarch="net"
else
  echo "Unknown Charm architecture: $arch !"
  exit 1
fi
}

printHelp()
{
  echo "`basename $0` [mpirun_options...] <progname> [options...]"
  echo 
  echo mpirun_options:
  echo "-machinefile <machine-file name>"
  echo "          Take the list of possible machines to run on from the"
  echo "          file <machine-file name>.  This is a list of all available"
  echo "          machines; use -np <np> to request a specific number of machines."
  echo "-np <np>"
  echo "          specify the number of processors to run on"
  echo "-v        Verbose - throw in some comments"
  echo
}

End() 
{
  test -n "$nodefile" && /bin/rm -f $nodefile
  exit $1
}

if test $# -eq 0
then
  echo "`basename $0`: Missing: program name"
  exit 0
fi

while [ ! $# -eq 0 ]
do
  arg="$1"
  case "$arg" in
  -help)
     printHelp
     exit 0
     ;;
  -v)
     verbose=1
     ;;
  -np)
     shift
     nPE=$1
     ;;
  -np*)
     nPE=`echo $1 | sed -e 's/^-np//'`
     ;;
  -machinefile)
     shift
     mfile=$1
     ;;
  *)
     opts="$opts $1"
     ;;
  esac
  shift
done

if test x$mfile = x
then
  if test -n "$PBS_NODEFILE"
  then
    mfile=$PBS_NODEFILE
  elif test -n "$LSB_HOSTS"
  then  # tungsten
    mfile="/tmp/.mfile.$$"
    echo $LSB_HOSTS | sed 's/ /\n/g' | sort > $mfile
  fi
fi

if test x$mfile != x
then
  CharmArch
  if test "$charmarch" = "net"
  then
    ConvertMachinefile
    opts="$opts ++nodelist $nodefile"
  elif test "$charmarch" = "mpi"
  then
    opts="$opts -machinefile $mfile"
  fi
fi

trap 'End 1' 2

test x$nPE = x && nPE=1

test $verbose = 1 && echo charmrun +p$nPE $opts
exedir=`dirname $0`
$exedir/charmrun +p$nPE $opts
status=$?

End $status

