#!/bin/sh

# do a good check that java is found
which java >& /dev/null
if [ $? -ne 0 ];then
   echo "java is not configured - alter your PATH environment or set up using mayobiotools"
   exit 1
fi

# exit if any statement returns a non-zero exit code
set -e

# Fix for excessive virtual memory usage
# newer glibc will allocate 64MB per thread
# this will limit 64MB to all threads for a process  
export MALLOC_ARENA_MAX=1

# check java version
REQUIRED_MINOR_VERSION=6

# grab full version string from running "java -version"
VERSION=`java -Xmx64m -version 2>&1 | grep "java version" | awk '{ print substr($3, 2, length($3)-2); }'`

# parse out the minor version number
MINOR_VERSION=`echo $VERSION | cut -d . -f 2`

# check minor version, anything less than the required version is invalid
if [ $MINOR_VERSION -lt $REQUIRED_MINOR_VERSION ]; then
	echo "Invalid Java version $VERSION.  Java 1.$REQUIRED_MINOR_VERSION or higher is required."
	echo "You can check your java version by running: java -version"
	exit 1
fi

# loop through all script arguments one by one
for var in "$@"
do
        # check if argument is debug flag
        if [ "$var" == "-remote" ] || [ "$var" == "--remote-debug" ];then

                echo ""
                echo "This JVM will be suspended until a remote debugger is attached."
                echo ""

                # check if environment variable is set
                if [ -z "$CLI_JVM_DEBUG_PORT" ];then
                        # variable not set, use default
                        CLI_JVM_DEBUG_PORT=4000
                        echo "Using default port $CLI_JVM_DEBUG_PORT.  For a custom port use \"export CLI_JVM_DEBUG_PORT=<port_#>\" and retry the command."
                else
                        echo "Using custom port $CLI_JVM_DEBUG_PORT.  To revert back to the default port use \"unset CLI_JVM_DEBUG_PORT\" and retry the command."
                fi
                echo ""
                JVM_DEBUG_FLAGS="-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=$CLI_JVM_DEBUG_PORT,suspend=y"
        fi
done

java $JVM_DEBUG_FLAGS -Xmx128m -cp $BIOR_LITE_HOME/conf:$BIOR_LITE_HOME/lib/* edu.mayo.cli.CommandLineApp edu.mayo.bior.cli.cmd.SNPEffCommand $0 $@


