#!/bin/bash

BINDIR="`dirname "$0"`"
cd "$BINDIR/.."
BASEDIR="`pwd`"

displayUsage() {
    echo "Usage: $0 [OPTIONS]"
    echo "OPTIONS: "
    echo " -h, -help   Display this usage message"
    echo " -textonly   Do a non-graphical command line installation"
    echo " -extract    Extract the jar file, this can then be run manually (such as with custom Java options as arguments to the installer jar file)."
}

# install_mode can be:
# Default behaviour (graphical installer, forced to textonly mode in non-graphical environment
# manual setting to Textonly mode
# Extract mode to extract jar file
install_mode="default"


if [ "x$1" != "x" ]; then
    if [ "$1" == "-h" ] || [ "$1" == "-help" ] || [ "$1" == "--help" ] ; then
	displayUsage
	exit 0
    elif [ "$1" == "-textonly" ] || [ "$1" == "-text" ] || [ "$1" == "text" ] ; then
	install_mode="textonly"
    elif [ "$1" == "-extract" ] || [ "$1" == "--extract" ] || [ "$1" == "-x" ] ; then
	install_mode="extract"
    else
	displayUsage
	exit 0
    fi
fi


# Debugging with a msg box. Need double quotes around msg for $var expansion
#osascript -e "tell app \"System Events\" to display alert \"bindir is: $BINDIR\" as warning giving up after 10"
 
## But this doesn't work:
# http://stackoverflow.com/questions/23923017/osascript-using-bash-variable-with-a-space
#osascript -e "display notification \"$BINDIR\""
#osascript -e 'display notification "'"$BINDIR"'"'

# extract the JRE into /tmp and use its java to run the GS jar installer
# the /tmp/jre folder will be moved into GS3/packages by the GS3 installer

if [[ -e "$BASEDIR/Resources/Java/jre_bin" ]]; then
     cp "$BASEDIR/Resources/Java/jre_bin" /tmp/. && chmod +x "/tmp/jre_bin" #&& "/tmp/jre_bin" -o"/tmp" #&& rm "/tmp/jre_bin"
     # Clear the quarantine flag Mac security adds from the copied self-extracting JRE
     xattr -c "/tmp/jre_bin" 2>/dev/null || true
     
     # Now we can at last unpack the archive
     "/tmp/jre_bin" -o"/tmp"
     
     if [[ -e "/tmp/jre.tar" ]]; then
        rm /tmp/jre_bin
        # get the GS jar installer's name and run it with a dock icon (http://stackoverflow.com/questions/6006173/how-do-you-change-the-dock-icon-of-a-java-program)
        cd "$BASEDIR/Resources/Java/"
        gs_installer=`ls Greenstone-*-MacOS-intel.jar`
        export JRE_HOME=/tmp/jre
        export PATH=$JRE_HOME/bin:$PATH
        #tar -xvf /tmp/jre.tar -C /tmp && rm /tmp/jre.tar && "/tmp/jre/bin/java" -jar -Xdock:icon="$BASEDIR/Resources/icon.icns" "$gs_installer"

	tar -xvf /tmp/jre.tar -C /tmp && rm /tmp/jre.tar
	# Clear the inherited quarantine attribute from the newly unpacked JRE folder
        xattr -cr "/tmp/jre" 2>/dev/null || true
	
	if [ "$install_mode" = "extract" ] ; then
	    # no need to extract: installer jar file already available in mac app
	    echo ""
	    echo "(Extracting jar file on mac is superfluous: the jar file is already ready for use at $gs_installer)"
	    echo "You can now run '/tmp/jre/bin/java -jar \"$BASEDIR/Resources/Java/$gs_installer\" text'"
	    echo "  to run the installer from the command line."
	    echo "Once you're finished with the installer, you can run \"rm -rf /tmp/jre\" to get rid of the temporary Java Runtime."
	    echo "Note: if the installer fails to run due to insufficient memory, try preceding the -jar with -Xmx300M in the above command."
	    echo ""
	elif [ "$install_mode" = "textonly" ] ; then
	    "/tmp/jre/bin/java" -Xmx300M -jar "$gs_installer" "text"
	else # "$install_mode" = "default", run the usual graphical GS3 mac installer
	    # which already falls back to textonly mode if no graphical environment available
	    "/tmp/jre/bin/java" -jar -Xdock:icon="$BASEDIR/Resources/icon.icns" "$gs_installer"
	fi
	
        # if after running the installer, the user cancelled installation, then the jre would still be in tmp, remove it to
	if [ "$install_mode" != "extract" ] ; then
            if [[ -e "/tmp/jre" ]]; then
		rm -rf /tmp/jre
            fi
	fi
     else
       # Issues extracting the jre.tar into /tmp (maybe we couldn't even copy it there) - display error message
       # see: https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW11
        osascript -e "tell app \"System Events\" to display alert \"Unable to unpack jre into /tmp folder\" as warning giving up after 10"   
       # exit
     fi
else
    # try using a system java to run the installer, as there is no bundled jre_bin for 32 bit Mac OS since these already came with java installed
  " -h, -help   Display this usage message"

    # get the GS jar installer's name and run it with a dock icon (http://stackoverflow.com/questions/6006173/how-do-you-change-the-dock-icon-of-a-java-program)
    cd "$BASEDIR/Resources/Java/"
    gs_installer=`ls Greenstone-*-MacOS-intel.jar`

    # on a mac, the system java is returned by running /usr/libexec/java_home
    # use this to run the greenstone installer
    `/usr/libexec/java_home`/bin/java -jar -Xdock:icon="$BASEDIR/Resources/icon.icns" "$gs_installer"
fi
