#!/bin/sh -e

# This script runs Goby with the specified amount of memory.

# Usage: goby mem-requirement mode-name [param]+
# Where mem-requirement indicates how much memory Goby should be given (e.g., 1g, 500m).
# Mode-name should specify a Goby mode.
# For instance, the following command will display the Goby version number:

#     goby 40m version
if [ $# -lt 1 ]; then
  echo "The first argument must be memory (i.e., goby 4g)"
  exit 1
fi

memory_requirement=$1
shift
other_parameters=$*
set +x

if [ ! -e ~/.goby ]; then
    mkdir ~/.goby
    mkdir ~/.goby/config
fi
export GOBY_HOME="~/.goby"
GOBY_JAR=/usr/share/java/goby.jar
SLF4J_CONFIG=${GOBY_HOME}/config/goby-logback.xml

cat >/tmp/r-cmd.txt <<EOT
system.file("jri",package="rJava")
EOT
tmpWithQuotes=`R --no-save </tmp/r-cmd.txt|grep "\[1\]"|tail -1 |awk '{print $2}'`
temp="${tmpWithQuotes%\"}"
temp="${temp#\"}"
export RJAVA_HOME=${temp}
rm -f /tmp/r-cmd.txt

DL_SOMATIC_CLASSPATH=${GOBY_HOME}/somatic.jar
if [ ! -e "${DL_SOMATIC_CLASSPATH}" ]; then
    echo "Model somatic.jar not found."
fi
DL_GENOTYPE_CLASSPATH=${GOBY_HOME}/genotype.jar
if [ ! -e "${DL_SOMATIC_CLASSPATH}" ]; then
    echo "Model genotype.jar not found."
fi
DL_FRAMEWORK_CLASSPATH=${GOBY_HOME}/framework.jar
if [ ! -e "${DL_FRAMEWORK_CLASSPATH}" ]; then
    echo "Model framework.jar not found."
fi

# Needed for running Rengine.
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$RJAVA_HOME"
export R_HOME="/usr/lib/R"

#echo java -ea -Xmx${memory_requirement} -Dlog4j.configuration=${LOG4J_PROPS} -Djava.library.path=${RJAVA_HOME} -jar ${GOBY_JAR} --mode ${other_parameters}
java -ea -cp "${GOBY_HOME}"  -Xmx${memory_requirement} -Dlogback.configurationFile=${SLF4J_CONFIG} -Djava.library.path=${RJAVA_HOME} -jar ${GOBY_JAR} --mode ${other_parameters}
if [ $# -lt 2 ]; then
  echo "The second argument must be the goby mode you want to run (i.e., goby 1g version). See list of modes in help above."
fi
