#!/bin/bash

## Copyright (c) The JAP-Team, JonDos GmbH
##
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without modification,
## are permitted provided that the following conditions are met:
##
##     * Redistributions of source code must retain the above copyright notice, this list
##   of conditions and the following disclaimer.
##     * Redistributions in binary form must reproduce the above copyright notice,
##       this list of conditions and the following disclaimer in the documentation and/or
##       other materials provided with the distribution.
##     * Neither the name of the University of Technology Dresden, Germany, nor the name of
##       the JonDos GmbH, nor the names of their contributors may be used to endorse or
##       promote products derived from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
## LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
## NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
## SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
##   JonDo client installation script for bash
##   2008 by Simon Pecher, JonDos GmbH (simon.pecher@jondos.de)
##

JONDOS_HOMEPAGE="https://www.jondos.de"

#default INSTALL_PATH is the users home directory
INSTALL_PATH="/usr/local"
JAVA_HOME_PATH=${JAVA_HOME}
JAVA_CMD="java"
#set placeholders for ant token filtering
#these values should be set by ant
ARGS="@ARGS@" 
APPNAME="@APPNAME@"
JARNAME="@JARNAME@"

#path of the installer
ROOT_DIR=$(dirname $0)

#don't leave the installpath dir in a mess when errors occur.
onErrorCleanupAndExit()
{
	rm -Rf "${INSTALL_PATH}/${APPNAME}"
	echo "${APPNAME} installation failed."
	echo
	exit 1
}

errorStarter()
{
	echo "Error creating ${APPNAME} Starter."
	rm -f "${STARTER}" 
	onErrorCleanupAndExit	
}

#print help text
printHelpText()
{
	echo "${APPNAME} installation for Linux, (2008 Copyright (c) JonDos GmbH, ${JONDOS_HOMEPAGE})"
	echo "usage: $0 [options] installpath"
	echo
	echo "The following files will be installed:"
	echo
	echo " [installpath]/${APPNAME}/${JARNAME}.jar"
	echo " [installpath]/bin/${APPNAME_LOWERCASE}"
	echo
	echo "If not specified installpath defaults \"/usr/local\"." 
	echo
	echo "Options are:"
	echo "  -h -?                   shows this help text"
	echo "  -j java_home_path       to specify the path where your java VM is installed,"
	echo "                          (the directory of the command 'java' without the trailing 'bin')."
	
}

javaCheck()
{
	$JAVA_CMD -version >& /dev/null && return 0
	echo "WARNING: Java VM installation $JAVA_CMD not found."
	echo "${APPNAME} will not be able to run without Java."
	echo "You can continue with the installation but you have to set JAVA_HOME to your"\
	     "Java VM installation path (the directory of the command 'java' without the trailing 'bin')"\
	     "before starting jondo."
	echo
	echo -n "Do you want to continue? (y/n) "
	read -n 1 jCheckanswer
	echo
	case ${jCheckanswer} in
		y*) JAVA_CMD="java"
		    JAVA_HOME_PATH="";;
 		*)  echo "${APPNAME} was not installed."; exit 1;;
	esac
	echo
}

#check if gnu classpath java is installed
gcjCheck()
{
	$JAVA_CMD -version 2>&1 | grep -i gnu\ >& /dev/null
	if [ $? -eq 0 ]; then
		echo "WARNING: GNU Java installation found. ${APPNAME} will not be able to run with GNU Java."\
		     "Please install a SUN JRE to run ${APPNAME}, (www.java.sun.com)."
		echo
		echo -n "Do you want to continue? (y/n) "
		read -n 1 gjCheckanswer
		echo
		case ${gjCheckanswer} in
			y*) JAVA_CMD="java"
			    JAVA_HOME_PATH="";;
 			*)  echo "${APPNAME} was not installed."; exit 1;;
		esac
		echo
	fi
}

#if no filtering was done, replace the token placeholders with default values
args_token=$(expr "${ARGS}" : "@\(.*\)@")
if  [ "${args_token}" = "ARGS" ]; then
	ARGS=""
fi

appname_token=$(expr "${APPNAME}" : "@\(.*\)@")
if  [ "${appname_token}" = "APPNAME" ]; then
	APPNAME="JonDo"
fi

jarname_token=$(expr "${JARNAME}" : "@\(.*\)@")
if  [ "${jarname_token}" = "JARNAME" ]; then
	JARNAME="JAP"
fi

#the name of the Jondo Starter should be in lowercase
APPNAME_LOWERCASE=$(echo "$APPNAME" | tr "[:upper:]" "[:lower:]" || echo "$APPNAME")

##start of the main routine
#read the commandline arguments
OPTSTR="?j:h"	
getopts "${OPTSTR}" CMD_OPT
while [ $? -eq 0 ]; 
do
	case ${CMD_OPT} in
		j)
			#if a relative path is specified complete it to an absolute path.
			JAVA_HOME_PATH=${OPTARG}
			absJPath=$(expr ${JAVA_HOME_PATH} : "\(^/.*\)")
			if [ -z "$absJPath" ]; then
				JAVA_HOME_PATH="$(pwd)/${JAVA_HOME_PATH}"
			fi
			;;
		h | ?)
			printHelpText; 
			exit 0;;
		*)	
			echo "unrecognized option: ${CMD_OPT}"
		   	printHelpText
		   	exit 1;;
	esac
	getopts "${OPTSTR}" CMD_OPT
done

shift $[$OPTIND-1]
if [ "$1" != "" ]; then
	INSTALL_PATH=$1
elif [ "${INSTALL_PATH}" = "" ]; then
	INSTALL_PATH="/usr/local" #if nothing is set: default install path is /usr/local
fi

#if a relative path is specified complete it to an absolute path.
absPath=$(expr $INSTALL_PATH : "\(^/.*\)")
if [ -z "$absPath" ]; then
	INSTALL_PATH="$(pwd)/${INSTALL_PATH}"
fi

#complete path of the starter
STARTER_ROOT="${INSTALL_PATH}/bin"
STARTER="${STARTER_ROOT}/${APPNAME_LOWERCASE}"

#set java command for java checks
if [ "${JAVA_HOME_PATH}" ]; then
	JAVA_CMD=${JAVA_HOME_PATH}/bin/java 
fi

#do the java checks
javaCheck
gcjCheck

#get the users confirmation
echo "${APPNAME} installation for Linux, (2008 Copyright (c) JonDos GmbH, ${JONDOS_HOMEPAGE})"
echo "Installing ${APPNAME} to ${INSTALL_PATH}, this will create:"
echo "   1. the directory '${INSTALL_PATH}/${APPNAME}',"
echo "   2. the file '${INSTALL_PATH}/${APPNAME}/${JARNAME}.jar'"
echo "   3. the file '${STARTER}'"
echo -n "Do you want to continue? (y/n) "
read -n 1 answer
echo
case ${answer} in
	y*);;
 	*) echo "${APPNAME} was not installed."; exit 1;;
esac

#install JAP.jar
install -Dvm 755 "${ROOT_DIR}/${JARNAME}.jar" "${INSTALL_PATH}/${APPNAME}/${JARNAME}.jar"

if [ $? -ne 0 ]; then
	onErrorCleanupAndExit
fi

#make sure the bin dir for the JonDo starter exists
if [ -d "${STARTER_ROOT}" ]; then
	echo "Directory ${STARTER_ROOT} exists."
else
	echo "creating directory ${STARTER_ROOT}"
	mkdir "${STARTER_ROOT}" || onErrorCleanupAndExit
fi

#create the JonDo starter (the appname in lower case by convention)
echo '#!/bin/bash' 								 > ${STARTER} || errorStarter
echo  										>> ${STARTER} || errorStarter
echo "JAVA_HOME_PATH=\"${JAVA_HOME_PATH}\""					>> ${STARTER} || errorStarter
echo 'JAVA_CMD="java"'								>> ${STARTER} || errorStarter
echo										>> ${STARTER} || errorStarter
echo 'javaCheck()'								>> ${STARTER} || errorStarter
echo '{'									>> ${STARTER} || errorStarter
echo '   $JAVA_CMD -version >& /dev/null && return 0'				>> ${STARTER} || errorStarter
echo '   echo "ERROR: Java VM ${JAVA_CMD} not found. Please set JAVA_HOME to the path of a valid Java VM installation"\'\
										>> ${STARTER} || errorStarter
echo '        "(the directory of the command \"java\" without the trailing \"bin\")."'\
										>> ${STARTER} || errorStarter
echo "   return 1"  								>> ${STARTER} || errorStarter
echo '}'									>> ${STARTER} || errorStarter
echo										>> ${STARTER} || errorStarter
echo 'gcjCheck()'								>> ${STARTER} || errorStarter
echo '{'									>> ${STARTER} || errorStarter
echo '   $JAVA_CMD -version 2>&1 | grep -i gnu\ >& /dev/null || return 0;'	>> ${STARTER} || errorStarter
echo "   echo \"ERROR: GNU Java installation found. ${APPNAME} will not be able to run with GNU Java.\"\\"\
										>> ${STARTER} || errorStarter
echo "        \"Please install a SUN JRE to run ${APPNAME}, (www.java.sun.com).\""\
										>> ${STARTER} || errorStarter
echo "   return 1"  								>> ${STARTER} || errorStarter
echo '}'									>> ${STARTER} || errorStarter
echo										>> ${STARTER} || errorStarter
echo 'if [ "${JAVA_HOME}" ]; then'						>> ${STARTER} || errorStarter
echo '   if [ "${JAVA_HOME_PATH}" -a ! "${JAVA_HOME}" -ef "${JAVA_HOME_PATH}" ]; then'\
										>> ${STARTER} || errorStarter
echo '      echo "WARNING: JAVA_HOME is set to ${JAVA_HOME}, your specified path ${JAVA_HOME_PATH} will be ignored."\'\
										>> ${STARTER} || errorStarter
echo '           "If you want to use your specified path, please undefine JAVA_HOME."'\
										>> ${STARTER} || errorStarter
echo '   fi'									>> ${STARTER} || errorStarter
echo '   JAVA_HOME_PATH="${JAVA_HOME}"'						>> ${STARTER} || errorStarter
echo 'fi'									>> ${STARTER} || errorStarter
echo										>> ${STARTER} || errorStarter
echo 'if [ "${JAVA_HOME_PATH}" ]; then'						>> ${STARTER} || errorStarter
echo '   JAVA_CMD="${JAVA_HOME_PATH}/bin/java"'					>> ${STARTER} || errorStarter
echo 'fi'									>> ${STARTER} || errorStarter
echo										>> ${STARTER} || errorStarter
echo 'case "$1" in' 								>> ${STARTER} || errorStarter
echo '   --remove)'								>> ${STARTER} || errorStarter
echo "      if [ ! -w \"${INSTALL_PATH}/${APPNAME}\" -o ! -w \"${STARTER}\" ]; then "\
										>> ${STARTER} || errorStarter
echo "         echo \"You are not privileged to remove ${APPNAME}, please run this again as privileged user!\""\
										>> ${STARTER} || errorStarter
echo "         exit 1"  							>> ${STARTER} || errorStarter
echo "      fi" 								>> ${STARTER} || errorStarter
echo "      echo \"Uninstalling ${APPNAME}... This will delete:\""		>> ${STARTER} || errorStarter
echo "      echo \"   1. the directory '${INSTALL_PATH}/${APPNAME}',\""		>> ${STARTER} || errorStarter
echo "      echo \"   2. the file '${STARTER}'\""				>> ${STARTER} || errorStarter
echo "      echo \"   3. the ${APPNAME} config and help files\""		>> ${STARTER} || errorStarter
echo '      echo'								>> ${STARTER} || errorStarter
echo '      echo -n "Do you want to continue? (y/n) "' 				>> ${STARTER} || errorStarter
echo '      read -n 1 answer' 							>> ${STARTER} || errorStarter
echo '      echo' 								>> ${STARTER} || errorStarter
echo '      case ${answer} in' 							>> ${STARTER} || errorStarter
echo '         y*);;'       							>> ${STARTER} || errorStarter
echo "         *) echo \"${APPNAME} was not removed.\"; exit 1;;"  		>> ${STARTER} || errorStarter
echo '      esac' 								>> ${STARTER} || errorStarter
echo "      javaCheck && gcjCheck && \$JAVA_CMD -jar ${INSTALL_PATH}/${APPNAME}/${JARNAME}.jar -s --uninstall"\
										>> ${STARTER} || errorStarter
echo "      rm -Rv ${INSTALL_PATH}/${APPNAME}" 					>> ${STARTER} || errorStarter
echo '      exec rm -v $0 '							>> ${STARTER} || errorStarter
echo '      ;;'  								>> ${STARTER} || errorStarter
echo '   --help)'								>> ${STARTER} || errorStarter
echo "      javaCheck && gcjCheck && \$JAVA_CMD -jar ${INSTALL_PATH}/${APPNAME}/${JARNAME}.jar --help"\
										>> ${STARTER} || errorStarter
echo "      echo \"--remove                     Deletes all installed ${APPNAME} files\""\
										>> ${STARTER} || errorStarter
echo "      echo \"                             including directory ${INSTALL_PATH}/${APPNAME} and file ${STARTER}\";;"\
										>> ${STARTER} || errorStarter
echo "   *) javaCheck && gcjCheck && \$JAVA_CMD -jar ${INSTALL_PATH}/${APPNAME}/${JARNAME}.jar ${ARGS} \$@;;"\
										>> ${STARTER} || errorStarter
echo 'esac' 									>> ${STARTER} || errorStarter
echo	  									>> ${STARTER} || errorStarter
chmod 755 									   ${STARTER} || errorStarter

#installation successful. print success message and some additional infos.
echo
echo "${APPNAME} was successfully installed to ${INSTALL_PATH}."
echo "Now type '${APPNAME_LOWERCASE}' to start the ${APPNAME} client."\
     "(If that does not work try '${STARTER}' or add '${STARTER_ROOT}' to your PATH variable with:"\
     "'export PATH=\${PATH}:${STARTER_ROOT}')"
echo
echo "With '${APPNAME_LOWERCASE} --remove' you can cleanup the ${APPNAME} installation" 
echo "For more information type '${APPNAME_LOWERCASE} --help' or visit '${JONDOS_HOMEPAGE}'"

exit 0