#!/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 that Java meets the minimum required version  (this code comes from the mayo-commons-cli-plugin project)
REQUIRED_MINOR_VERSION=6

# 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=`java -Xmx64m -version 2>&1 | head -1 | cut -f3 -d' ' | tr -d '"'`

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

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

# 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
