#! /bin/sh

# if defined, prepend R_SNOW_LIB to $_LIBS
if test ! -z "${R_SNOW_LIB}" ; then
    R_LIBS=${R_SNOW_LIB}:${R_LIBS}; export R_LIBS
fi

# find the library containing the snow package; should eventually use Rscript
snowdir=`echo 'invisible(cat(tryCatch(dirname(.find.package("snow")), error = function(e) ""),"\n",sep=""))' | R --slave`

# for now this hijacks the R_PROFILE mechanism to start up the R
# sessions and load snow and Rmpi into them
R_PROFILE=${snowdir}/snow/RMPISNOWprofile; export R_PROFILE

if test ! -z "${LAMRANK}" ; then
    # use the LAMRANK environment variable set by LAM-MPI's mpirun to
    # run R with appropriate arguments for master and workers.
    if test "${LAMRANK}" == "0" ; then
	exec R $*
    else
	exec R --slave > /dev/null 2>&1
    fi
else 
    # It should be possible to do something similar in OpenMPI using
    # OMPI_MCA_ns_nds_vpid or OMPI_MCA_ns_nds_vpid_start to send different
    # arguments to master and worker processes
    # The fallback is to use the same arguments on master and workers,
    # with --no-save for cases where workers don't have a terminal.
    # This means that things like CMD batch won't work. It seems to be
    # important NOT to use exec here, at least when this code runs under LAM.
    R --no-save $*
fi
