#!/usr/bin/env sh
MIN_VERSION="1.7"
echoerr() { echo "$@" 1>&2; }

if type -p java >/dev/null; then
#    echo found java executable in PATH
    _java=java
elif [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]];  then
#    echo found java executable in JAVA_HOME     
    _java="$JAVA_HOME/bin/java"
else
    echoerr -e "\033[1;31mError:\033[0m K requires Java $MIN_VERSION to run but Java was not detected."
    echoerr "Please either add it to PATH or set the JAVA_HOME environment variable."
    exit 1
fi

if [[ "$_java" ]]; then
    version=$("$_java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
#    echo version "$version"
    if ! [[ "$version" > "$MIN_VERSION" ]]; then
        echoerr -e "\033[1;31mError:\033[0m K requires Java $MIN_VERSION to run but the detected version is $version."
        echoerr "Please either add Java $MIN_VERSION bin directory to the PATH or set the JAVA_HOME 
environment variable accordingly."
	exit 2
    fi
fi

