#!/bin/sh

PRG=$0
PROGDIR=`dirname "$PRG"`

cd "$PROGDIR"/../../
AppPackageFolder=`pwd`

cd ..
AppPackageRoot=`pwd`
cd ..
AppRoot=`pwd`

InfoPlistFile="${AppPackageFolder}"/Contents/Info.plist

JVMVersion=""

JAVA_HOME=${AppRoot}/jvm

ResourcesFolder="${AppPackageFolder}"/Contents/Resources

APP_PACKAGE="${AppPackageFolder}"

USER_HOME="$HOME"

// Get variables from plist
CFBundleName=`/usr/libexec/PlistBuddy -c "print :CFBundleName" "${InfoPlistFile}"`

CFBundleIconFile=`/usr/libexec/PlistBuddy -c "print :CFBundleIconFile" "${InfoPlistFile}"`

JVMWorkDir=`/usr/libexec/PlistBuddy -c "print :WorkingDirectory" "${InfoPlistFile}" 2> /dev/null | xargs`

if [[ ! -z ${JVMWorkDir} ]]; then
	WorkingDirectory="${JVMWorkDir}"
else
	WorkingDirectory="${AppPackageRoot}"
fi

JVMMainClass=`/usr/libexec/PlistBuddy -c "print :MainClass" "${InfoPlistFile}" 2> /dev/null`

JVMOptions=`/usr/libexec/PlistBuddy -c "print :Properties" "${InfoPlistFile}" 2> /dev/null | grep " =" | sed 's/^ */-D/g' | tr '\n' ' ' | sed 's/  */ /g' | sed 's/ = /=/g' | xargs`

JVMClassPath=`/usr/libexec/PlistBuddy -c "print :ClassPath" "${InfoPlistFile}" 2> /dev/null`

JVMDefaultOptions=`/usr/libexec/PlistBuddy -c "print :VMOptions" "${InfoPlistFile}" 2> /dev/null | xargs`

JVMArguments=`/usr/libexec/PlistBuddy -c "print :Arguments" "${InfoPlistFile}" 2> /dev/null | xargs`

JVMVersion=`/usr/libexec/PlistBuddy -c "print :JVMVersion" "${InfoPlistFile}" 2> /dev/null | xargs`

JAVACMD="$JAVA_HOME/bin/java"

if [ -f "$JAVACMD" ] && [ -x "$JAVACMD" ] ; then

	export CFProcessPath="$0"

	cd "${WorkingDirectory}"

	exec "$JAVACMD" \
            -cp "${JVMClassPath}" \
            -Xdock:icon="${ResourcesFolder}/${CFBundleIconFile}" \
            -Xdock:name="${CFBundleName}" \
            ${JVMOptions:+$JVMOptions }\
            ${JVMDefaultOptions:+$JVMDefaultOptions }\
            ${JVMMainClass}\
            ${JVMArguments:+ $JVMArguments}
fi
