#!/bin/bash
# NOTE: On some systems, /bin/sh is just a symlink to /bin/bash, so be explicit in declaring the shell above to be bash

# For error messages, direct them to STDERR instead of STDOUT
echoerr() { (>&2  echo "$@") }

# do a good check that java is found (redirect both STDOUT and STDERR to /dev/null).
# Then check the exit code of the "command -v" command
command -v java > /dev/null 2>&1
if [ $? -ne 0 ];then
    echoerr "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 (ex: required major=1, minor=6)
REQUIRED_MAJOR_VERSION=1
REQUIRED_MINOR_VERSION=6
REQUIRED_VERSION_SUM=$(( (REQUIRED_MAJOR_VERSION * 100) + REQUIRED_MINOR_VERSION))

# Temporarily turn off the exit on non-zero error code so we can test a call to Java
set +e
# Test that we can actually call Java (without all the extra Linux commands)
FULL_JAVA_VERSION=`java -Xmx64m -version 2>&1`
if [ $? -ne 0 ] ; then
    echoerr "Unable to run command:  Java -Xmx64m -version"
    echoerr "$FULL_JAVA_VERSION"
    exit 1
fi
set -e

# grab full version string from running "java -version"
# Example output of "java -version":  java version "1.7.0_111"   or   openjdk version "1.7.0_91"
# Example VERSION:  1.7.0_91
VERSION=`echo "$FULL_JAVA_VERSION" | grep "version" | head -1 | cut -f3 -d' ' | tr -d '"'`


# parse out the major version number (ex: "1" from "1.7.0_91" or "10" from "10.0.1")
# parse out the minor version number (ex: "7" from "1.7.0_91" or "0" from "10.0.1")
MAJOR_VERSION=`echo $VERSION | cut -d'.' -f 1`
MINOR_VERSION=`echo $VERSION | cut -d'.' -f 2`

if [ -z "$MAJOR_VERSION" ] ; then
    echoerr "Could not determine the major Java version"
    echoerr "You can check your java version by running: java -version"
    exit 1
fi

if [ -z "$MINOR_VERSION" ] ; then
    echoerr "Could not determine the minor Java version"
    echoerr "You can check your java version by running: java -version"
    exit 1
fi

intRegex='^[0-9]+$'
if ! [[ $MAJOR_VERSION =~ $intRegex ]] ; then
    echoerr "The Java major version is not an integer: $MAJOR_VERSION"
    exit 1
fi
if ! [[ $MINOR_VERSION =~ $intRegex ]] ; then
    echoerr "The Java minor version is not an integer: $MINOR_VERSION"
    exit 1
fi

# To ensure major version dominates minor version, multiple major by 100, then add to minor
VERSION_SUM=$(( (MAJOR_VERSION * 100) + MINOR_VERSION))

# check version (major and minor), anything less than the required version is invalid
if [ "$VERSION_SUM" -lt "$REQUIRED_VERSION_SUM" ]; then
    echoerr "Invalid Java version $VERSION.  Java $REQUIRED_MAJOR_VERSION.$REQUIRED_MINOR_VERSION or higher is required."
    echoerr "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


# Get the script path so we can use it to set the classpath variable to the relative conf and lib dirs
# NOTE: The Mac readlink command does not recognize the "-f" flag and will throw an error.
#       Instead, use the python readpath call to do the same thing
OS_NAME=$(uname -s)
if [ "$OS_NAME" == 'Darwin' ] ; then
    SCRIPT_PATH=$(python -c "import os,sys; print os.path.realpath(\"$0\")")
else
    SCRIPT_PATH=$(readlink -f "$0")
fi
SCRIPT_BIN_DIR=$(dirname "$SCRIPT_PATH")


# NOTE: You can specify additional arguments like the heap size by declaring CLI_JVM_ARGS in your shell environment.
# Example:
#   export CLI_JVM_ARGS=-Xmx512M
java $JVM_DEBUG_FLAGS -Xmx128m $CLI_JVM_ARGS -cp $SCRIPT_BIN_DIR/../conf:$SCRIPT_BIN_DIR/../lib/* edu.mayo.cli.CommandLineApp edu.mayo.bior.cli.cmd.Tab2JSONCommand $0 "$@"


