#!/bin/bash

# Check that $BIOR_LITE_HOME variable has been set
if [ -z $BIOR_LITE_HOME ]; then
    echo "The environment variable BIOR_LITE_HOME is not set. Please initialize BIOR in your environment using mayobiotools to run this script."
    echo "Also add \$BIOR_LITE_HOME/bin to your PATH."
    exit 1
fi


# Check that java actually exists by checking the exit code when running "command" against it
command -v java 2>&1 >/dev/null
if [ $? -ne 0 ] ; then
  echo "Java not found.  Please add java to your path (or setup using mayobiotools) and retry the command"
  exit 1
fi


# 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

