#!/bin/sh
#
# Launch Script for InterMapper/RemoteAccess on Unix-like Systems.
#
# Email questions/comments/suggestions to "support.intermapper@helpsystems.com"
# quoting your InterMapper/InterMapper RemoteAccess product version.
#
imprefix="/usr/local"
javacmds="/usr/local/bin/java /usr/bin/java /usr/java/latest/bin/java /usr/java/bin/java /usr/lib/jvm/java-*-sun/jre/bin/java"
javabase="/usr/java /usr/lib /usr/local '$HOME'"
javadirs="jre j2re j2sdk jdk1. SunJava2- linux-sun-jdk"
grepcmd="grep"
# javaDotCom="java.com"
javaDotCom="openjdk.java.net"

if [ -n "$INTERMAPPER_JAVA" ]; then
	javapath="$INTERMAPPER_JAVA"
elif [ -d "${imprefix}/share/intermapper/jre" ]; then
	imjavahome="${imprefix}/share/intermapper/jre"
	javapath="${imjavahome}/bin/java"
else
	javapath="java"
fi

# As of IM v6.4 "IM Console" and "IM Remote Access" require a minimum Java version of 11
minjavaversion="11.0"

# This script operates in two modes.
# The default mode launches InterMapper with the following default settings.

imtype=""
workdir="$imprefix/share/intermapper"
jarfile="$imprefix/share/intermapper/intermapper.jar"

# If this script finds the file "intermapper_remoteaccess.jar" in the script directory,
# then we launch InterMapper RemoteAccess instead.

scriptdir=`dirname "$0"`
if [ "$scriptdir" = "." ]; then
	scriptdir=`pwd`
fi

if [ -f "$scriptdir/intermapper_remoteaccess.jar" ]; then
	imtype=" RemoteAccess"
	workdir="$scriptdir"
	jarfile="$scriptdir/intermapper_remoteaccess.jar"
fi


# function: javaversion <arg>
#
# <arg> is a 'java' executable
#
# java -version outputs a line: java version "#.#.#_#"
# We convert to a number XYY, e.g. 1.7.2_34 becomes 107
#
javaversion()
{
	interpreter="$1"

	# Use the "--version" option by preference because (where supported) it has fixed the
	# error in the original spec for "-version" by outputting on standard output not on
	# standard error output.  Such quality implicitly warrants for its future stability.
	#
	v1=`"${interpreter}" --version 2>/dev/null     | sed -n -e '/^openjdk/s/^.* \([0-9][0-9._-]*\) [0-9][0-9-]*$/\1/p'`
	v2=`"${interpreter}"  -version 2>&1 >/dev/null | sed -n -e '/openjdk version/s/^.*"\([0-9][0-9._-]*\)".*$/\1/p'`
	v3=`"${interpreter}"  -version 2>&1 >/dev/null | sed -n -e '/java version/s/^.*"\([0-9][0-9._-]*\)".*$/\1/p'`

	if [ -n "$v1" ] ; then
		v="$v1"
	elif [ -n "$v2" ] ; then
		v="$v2"
	else
		v="$v3"
	fi

	if [ -n "$v" ] ; then
		echo "$v" | sed -e 's/[._-]/ /g'
	else
		#
		# Otherwise fall back on the original Dartware code.
		#
		"${interpreter}" -version 2>&1 | \
			grep -E '(java|openjdk) version' | \
			sed -e 's/.* \([^ ]\{1,\}\)/\1/' \
				-e 's/\"//g' \
				-e 's/\./ /g'
	fi | awk '{ printf("%d%02d\n", $1, $2); }'
}

# function: goodjava <arg>
#
# Return SUCCESS if <arg> points to an executable that is not the limited "GCJ"
# version of java distributed with some linux systems, and if it is of the
# required minimum version.

goodjava ()
{
	if [ -x "$1" ]; then
		gcj=`"$1" -version 2>&1 | "${grepcmd:-grep}" -E "(jdkgcj)|(libgcj)|(gcj )"`
		if [ -z "$gcj" ]; then
			minversion=`echo "${minjavaversion}" | sed -e 's/\./ /g' | awk '{ printf("%d%02d\n", $1, $2); }'`
			version=`javaversion "$1"`
			if [ -n "${version}" ] && [ "${version}" -ge "${minversion}" ]; then
				return 0					# version is good
			else
				FOUNDBADJAVA="We found a Java interpreter in \"$1\", but it is not suitable as a minimum Java version of ${minjavaversion} is required.  "
			fi
		else
			FOUNDBADJAVA="We found a Java interpreter in \"$1\", but it is a version of GCJ, which is not supported.  "
		fi
	fi
	
	return 1								# not found, not new enough version, or gcj java
}


# function: findjre
#
# Locate the path to a viable 'jre' on the current system. This function tries
# the sub-directories of ${javabase} listed by prefix in ${javadirs}.

findjre ()
{
	# If JAVA_HOME, JAVA_PATH, or JRE_HOME is set, prepend it to the front of $javabase.
	if [ -n "$JAVA_HOME" ]; then
		javabase="$JAVA_HOME $javabase"
	elif [ -n "$JAVA_PATH" ]; then
		javabase="$JAVA_PATH $javabase"
	elif [ -n "$JRE_HOME" ]; then
		javabase="$JRE_HOME $javabase"
	fi

	for jbase in $javabase; do
		if [ -d "$jbase" ]; then
			for jdir in $javadirs; do
				for jpath in `ls -1 -r -d -F "${jbase}/${jdir}"* 2>&- | "${grepcmd:-grep}" '/$'`; do
					if [ -n "$jpath" ]; then
						# For each java directory candidate, check if there is a bin/java
						# executable inside.
						if [ -x "${jpath}bin/java" ] && goodjava "${jpath}bin/java" ; then
							echo "${jpath}"
							return 0
						fi
					fi
				done
			done
		fi
	done

	return 1									# not found
}


# function: findjava
#
# Locate the path to a viable 'java' on the current system. This function first
# looks at well-known executable locations in ${javacmds}. It then relies on findjre
# to search the sub-directories of ${javabase} listed by prefix in ${javadirs}.

findjava ()
{
	# If JAVA_HOME or JAVA_PATH is set, prepend the likely Java path
	# ($JAVA_HOME/bin/java) to the front of $javacmds.
	if [ -n "$JAVA_HOME" ]; then
		javacmds="$JAVA_HOME/bin/java $javacmds"
	elif [ -n "$JAVA_PATH" ]; then
		javacmds="$JAVA_PATH/bin/java $javacmds"
	fi

	for cmd in $javacmds; do
		if goodjava "$cmd" ; then
			echo "$cmd"
			return 0
		fi
	done
	
	jrepath=`findjre`
	if [ -x "${jrepath}bin/java" ]; then
		echo "${jrepath}/bin/java"
		return 0
	fi
	
	return 1									# not found
}


# function: realpath <arg>
#
# Locate the full path name to the given command, if it is a shell script or program.
# Print "" if not found.

realpath ()
{
	if [ -n "$BASH" ]; then
		type -path "$1"							# -path option not supported in old sh
	else
		rp=`which "$1"`
		if [ $? -eq 0 -a -x "$rp" ]; then
           if [ `dirname "$rp"` = "." ]; then	# beware . in PATH env variable
                wd=`pwd`
                rp="$wd/$rp"
            fi
			echo "$rp"
		fi
	fi
}


# function: TotalPhysicalMemoryK
#
# Determine the total amount of physical memory (Kilobytes) available on the
# current system. This function only works on Linux systems that have a
# viable "/proc/meminfo" file.

TotalPhysicalMemoryK()
{
	osname=`uname -s`
	if [ "$osname" = "Linux" ]; then
		if [ -e "/proc/meminfo" ]; then
			# Extract number of kilobytes from "MemTotal" line in /proc/meminfo
			# then print just this value to stdout: "MemTotal:  126376 kB"
			sed -n '/^MemTotal:.*kB$/s/.* \([0-9]*\) kB$/\1/p' < /proc/meminfo
		fi
	fi
	return 0
}


# function: JavaHeapSizeArgs
#
# Specify desirable heap size limits for a Java VM running on the current
# system. By default, a Java VM allows a maximum heap size of 64 MB. We up the
# max heap size to 1/2 the physical RAM on the machine. We set the initial heap
# size to 16 MB to make application startup faster.
#
# If we cannot determine the amount of physical RAM or the amount of RAM is too
# low, this function does not return any extra heap-size arguments; we use
# the defaults supplied by the VM.

JavaHeapSizeArgs()
{
	javaMemDefMax="65536"
	javaMemMin="16384"
	javaMemAbsMax="1571840"
	physMemTotal=`TotalPhysicalMemoryK` 
	if [ -n "$physMemTotal" ]; then
		javaMemMax=`expr $physMemTotal / 2`
		# 1535M is the largest that Java can handle on most 32-bit
		# Intel implementations. 64-bit versions could handle more,
		# if we wanted to special-case them. CLS.
		if [ $javaMemMax -ge $javaMemAbsMax ]; then
			javaMemMax=$javaMemAbsMax
		fi
		if [ $javaMemMax -ge $javaMemDefMax ]; then
			echo "-Xms${javaMemMin}K -Xmx${javaMemMax}K"
		elif [ $javaMemMax -ge $javaMemMin ]; then
			echo "-Xms${javaMemMin}K -Xmx${javaMemDefMax}K"
		fi
	fi
	return 0
}

GUIMessage()
{
	if [ "$DISPLAY" = "" ]; then return 1 ; fi

	# If we're on a terminal, don't display GUI messages
	test -t 0
	if [ $? -eq 0 ] ; then return 1 ; fi

	# No space after '--text=' is intentional; zenity doesn't want one there.
	if [ -x "`which zenity`" ] ; then echo `which zenity` --error --text=; return 0; fi
	if [ -x "`which kdialog`" ] ; then echo `which kdialog` " --error " ; return 0; fi
	# xmessage is ugly and doesn't parse newlines properly, but it's all that 
	# is available on old systems; hopefully people are using modern desktops
	# so they don't see this!
	if [ -x "`which xmessage`" ] ; then echo `which xmessage` "-center " ; return 0; fi
	return 1
}

# MAIN SCRIPT STARTS HERE #

javapath=`realpath "$javapath"`

if [ -x "/usr/xpg4/bin/grep" ]; then		# prefer /usr/xpg4/bin/grep if available
	grepcmd="/usr/xpg4/bin/grep"
fi

goodjava "$javapath"			
if [ $? -ne 0 ]; then							# no ! operator in old sh
	javapath=`findjava`
fi

messager=`GUIMessage`
if [ $? -eq 0 ]; then
	have_messager=1
else
	have_messager=0
fi

# Separate Java options from InterMapper options

found_args=0
found_help=0
for arg in "$@"
do
	if [ "x${arg}" = "x-args" ] ; then
		found_args=1
	elif [ "${found_args:-0}" -eq 0 ] && [ "x${arg}" = "x-h" ] ; then
		found_help=1
	else
		if [ "${found_args:-0}" -eq 1 ]; then
			IM_ARGS="$IM_ARGS $arg"
		else
			JAVA_ARGS="$JAVA_ARGS $arg"
		fi
	fi
done


if [ -n "$javapath" ]; then

	if [ -z "$JAVA_ARGS" ] ; then
		JAVA_ARGS=`JavaHeapSizeArgs`
	fi
	
	if [ -n "$imjavahome" ]; then
		jrepath="$imjavahome"
	else
		jrepath=`findjre`
	fi

	if [ -e "$jrepath/lib/jfxrt.jar" ]; then
		JAVA_ARGS="$JAVA_ARGS -Xbootclasspath/a:$jrepath/lib/jfxrt.jar"
	fi

	if [ $found_help = 1 ]; then
		if [ $have_messager -eq 1 ]; then
			$messager"This script is designed to launch InterMapper${imtype} using the\nlatest Java software found on your system. Here is the command line\nthat this script will use (when invoked with no arguments):\n\n  cd \"$workdir\"\n  \"$javapath\" $javaArgs -jar \"$jarfile\""
	    fi
	    echo "Usage: $0 [-h]"
		echo "   or: $0 [java options] [-args InterMapper${imtype} options]"
	    echo
	    echo "This script is designed to launch InterMapper${imtype} using the"
	    echo "latest Java software found on your system. Here is the command line"
	    echo "that this script will use (when invoked with no arguments):"
	    echo
	    echo "  cd \"$workdir\""
	    echo "  \"$javapath\" $JAVA_ARGS -jar \"$jarfile\" $IM_ARGS"
	    echo
		echo "Run '\"$javapath\" -help' to see the available java options."
		echo "Run '$0 -args -help' to see the available InterMapper${imtype} client options."
	    exit 1
	elif [ -f "$jarfile" ]; then
		# Start the Java Application!!
		cd "$workdir"
		if [ $have_messager -eq 1 ]; then
			mesg=`"$javapath" $JAVA_ARGS -jar "$jarfile" $IM_ARGS 2>&1`
			err=$?
			if [ $err -eq 88 ] ; then
				$messager$mesg
			fi
		else
			"$javapath" $JAVA_ARGS -jar "$jarfile" $IM_ARGS
			err=$?
		fi
		exit $err
	else
		if [ $have_messager -eq 1 ]; then
			$messager"This script cannot locate InterMapper${imtype}.  There is no .jar file at the expected location:\n\n	 ${jarfile}"
		fi
	    echo "Usage: $0 [-h]"
	    echo
	    echo "This script cannot locate InterMapper${imtype}. There is no .jar"
	    echo "file at the expected location:"
	    echo 
	    echo "  ${jarfile}"
	    echo
	    exit 1
	fi
	
else
	if [ "$have_messager" -eq "1" ]; then
		$messager"InterMapper is unable to locate the Java software on this system. Java is required to run InterMapper${imtype}. $FOUNDBADJAVA Please visit '${javaDotCom}' to download and install the Java Software, then re-run this program.\n\nIf you have installed Java in a non-standard location, please set the environment variable 'INTERMAPPER_JAVA' to the full path name of your 'java' executable, then re-run this program."
	fi
    echo "Usage: $0 [-h]"
    echo
    echo "InterMapper is unable to locate the Java software on this system."
    echo "Java is required to run InterMapper${imtype}."
	echo $FOUNDBADJAVA
	echo "Please visit '${javaDotCom}' to download and install the Java Software,"
	echo "then re-run this program."
    echo 
    echo "If you have installed Java in a non-standard location, please set the"
    echo "environment variable 'INTERMAPPER_JAVA' to the full path name of your"
    echo "'java' executable, then re-run this program."
    echo 
    exit 1
fi

# MAIN SCRIPT ENDS HERE #
