#!/bin/bash
set -e

#
# This script will take into consideration the following environment variables, if defined:
#
#  SINCERITY_HOME
#    The root of the Sincerity installation to use. If not provided, will automatically
#    discover it according to actual (not symlinked) location of this script file
#  JAVA_HOME
#    The root of the JVM installation. If not provided, will use a platform-specific
#    heuristic to discover it.
#  JAVA_VERSION
#    Used only in Darwin (Mac OS X). Defaults to "CurrentJDK".
#  JVM_LIBRARIES
#    Extra libraries to add to the classpath.
#  JVM_SWITCHES
#    Extra switches to add to the JVM invocation.
#

get-parent-path()
{
	# Finds the parent directory, following symlinks

	local THE_PATH=$1

	set +e
	THE_PATH=$(readlink -f "$THE_PATH" 2> /dev/null)
	if (( "$?" == 0 )); then
		set -e
		dirname "$(readlink -f "$THE_PATH")"
	else
		# "readlink -f" works on Linux, but not on Darwin and OpenSolaris
		set -e
		local OLD_PWD=$PWD
		cd "$(dirname "$THE_PATH")"
		local HERE=$PWD
		cd "$OLD_PWD"
		echo "$HERE"
	fi
}

#
# Find JVM
#

OS=$(uname -s | tr '[:upper:]' '[:lower:]')

if [ -n "$JAVA_HOME" ]; then
	JAVA="$JAVA_HOME/bin/java"
	if [ ! -f "$JAVA" ]; then
		echo "JAVA_HOME does not point to a valid JVM directory" 1>&2
		exit 1
	fi
else
	case "$OS" in
		linux)
			JAVA=/usr/bin/java
			;;
		darwin)
			JAVA=/System/Library/Frameworks/JavaVM.framework/Home/bin/java
			;;
		sunos)
			JAVA=/usr/jdk/latest/bin/java
			;;
	esac
	if [ ! -f "$JAVA" ]; then
		echo "Could not find Java: please set JAVA_HOME to a JVM directory" 1>&2
		exit 1
	fi
fi

#
# Find JVM tools
#

if [ "$OS" == darwin ]; then
	if [ -z "$JAVA_VERSION" ] ; then
		JAVA_VERSION=CurrentJDK
	fi
	TOOLS="/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Classes/classes.jar"
else
	TOOLS="$JAVA_HOME/lib/tools.jar"
fi

#
# Find Sincerity home
#

if [ -z "$SINCERITY_HOME" ]; then
	SINCERITY_HOME=$(get-parent-path "$0")
fi

#
# Libraries
#

JVM_LIBRARIES="$JVM_LIBRARIES${JVM_LIBRARIES:+:}$SINCERITY_HOME/bootstrap.jar:$TOOLS"

#
# Sincerity
#

"$JAVA" \
$JVM_SWITCHES \
-Dsincerity.home="$SINCERITY_HOME" \
-Dfile.encoding=UTF-8 \
-classpath \
"$JVM_LIBRARIES" \
com.threecrickets.bootstrap.Bootstrap \
"$@"
