#!/bin/bash
#  OnsetPreFunctions for HOBOware installer
#
#
# Notes:  1) When expecting a directory as a parameter, this pattern is used: ${2%/}
#            This looks at the value of parameter 2 and checks if it ends in '/' and
#            if it does, it removes it. This means you MUST make sure a '/' follows
#            if you are appending to that directory.
#
#         2) To get the results of a command that would normally go to stdout into a
#            variable,you can enclose the command in parentheses with a $ preceding
#            the opening parenthesis. For instance, to get the group name from the
#            id command, this command would work: UserGroup=$(id -gn "$USER")
#            Now, UserGroup would have the first group to which the currently logged
#            on user belongs to.
#
#         3) One of the big problems we've had is dealing with spaces in file and
#            folder names. OS X allows spaces in file and folder names while UNIX
#            often balks at them. To deal with this, we need to enclose variables
#            in { } braces when they are used. For instance:
#            Path=/Users/Jim Dodd/Documents"
#            NewPath="${Path}"
#            The Braces allow the "Jim Dodd" to pass through without terminating the
#            string.
#
#         3) Watch out for putting a wildcard character, I've only checked '*', inside
#            double quotes when trying to get a range of file names. For instance,
#            if you want to get all the Jar files in a folder, this will cause a
#            problem:
#                        cp "$FileFolder/*.jar" "$TargetFolder"
#            The problem is that the shell will be looking for a file literally
#            named "*.jar" which is impossible. File names cannot include am asterisk.
#            Instead, use this method to get wildcard expansion:
#                        cp "$FileFolder"/*.jar "$TargetFolder"
#
#
#         4) If this is to be an Upgrade version of the installer, you must call the
#            upgrade check program (which looks for an existing copy of HOBOware Pro)
#            in this script with the $2 argument which points to where HOBOware Pro is
#            supposed to be.
#
#
# -- DEFINE FUNCTIONS USED LATER IN THE SCRIPT
#
#
# Writes debugging information out to HOBOwareInstall.txt file in user's home folder
#
function WriteLog {
  echo "$*"  >> ~/HOBOwareInstall.txt
}

#WriteLog ""
#WriteLog ""
#WriteLog "==================================================="
#date >> ~/HOBOwareInstall.txt
#chmod 666 ~/HOBOwareInstall.txt
WriteLog ""
WriteLog "Running OnsetPreFunctions script"
WriteLog "Parameters:"
let ParamCount=0
for param in "${@}"
do
	let ParamCount=ParamCount+1
	WriteLog "$ParamCount: ${param}"
	# first parameter is name of installer program (and path, basename removes path)
	if [ $ParamCount -eq 1 ]
	then
		InstallerName=$(basename "${param}")
	fi
done
WriteLog ""

#
# --- FIRST, LIST WHICH VERSION OF HOBOWARE WE ARE INSTALLING AND
#     WHICH VERSION OF THE INSTALLER WE ARE USING
WriteLog ""
ProgramVersion=3.4.0_20121220
InstallerSuffix=
InstallerVersion="$ProgramVersion$InstallerSuffix"
WriteLog "Installing HOBOware version $ProgramVersion"
if [ ${InstallerName} = "HOBOware.pkg" ]
then
	WriteLog "Installer version $InstallerVersion"
else
	WriteLog "Installer (updater) version $InstallerVersion"
fi

#
# --- CHECK THAT THE NAME OF THE INSTALLER FILE IS CORRECT
#     IT MUST BE HOBOware.pkg OR HOBOware_Updater.pkg
#
if [ ${InstallerName} = "HOBOware.pkg" ]
then
	WriteLog "This is an installer"
elif [ ${InstallerName} = "HOBOware_Updater.pkg" ]
then
	WriteLog "This is an updater"
else
	WriteLog "The installer name, '${InstallerName}', is incorrect"
	let retval=96
	exit $retval
fi
WriteLog ""

# -- CREATE A VARIABLE THAT WILL BE RETURNED AS NON-ZERO IS AN ERROR OCCURS
#    IT IS INITIALLY ZERO FOR NO ERRORS
#
let retval=0

#
# -- SECOND, CREATE FULL PATH TO WHERE HOBOWARE WILL BE INSTALLED
OldProPath="${2%/}/HOBOwarePro.app"
OldLitePath="${2%/}/HOBOwareLite.app"
NewAppPath="${2%/}/HOBOware.app" 

# -- first check if HOBOware Pro exists, if it does, just continue
#    if it does not, check if HOBOware exists, if it does, change
#    AppPath to point to that.
#
WriteLog "Preliminary check for existing HOBOware Pro application"
if test -e "${NewAppPath}"
then
	WriteLog "Previous HOBOware exists"
	AppPath="$NewAppPath"
elif test -e "${OldProPath}"
then
	WriteLog "Previous HOBOware Pro exists"
	AppPath="$OldProPath"
	echo "Sara" > "${2%/}//programtype.txt"
elif test -e "${OldLitePath}"
then
	WriteLog "Previous HOBOware Lite exists"
	AppPath="$OldLitePath"
	echo "Ginger" > "${2%/}//programtype.txt"
else 
	if [ ${InstallerName} = "HOBOware_Updater.pkg" ]
	then
		WriteLog "** This is an Updater and neither HOBOware Pro, HOBOware Lite nor HOBOware exist"
		let retval=96
		exit $retval
	else
		WriteLog "Neither HOBOware Pro, HOBOware Lite nor HOBOware exist"
		AppPath="$NewAppPath"
	fi
fi

ProcessorsPath="${AppPath}/Contents/Resources/Java/Processors"
ProcessorsHelpPath="${ProcessorsPath}/WebHelp"
PluginsPath="${AppPath}/Contents/Resources/Java/Plugins"
ExistingAlarmsTool="${PluginsPath%/}/Alarms/AlarmsTool.jar"
NewProcessorsPath="${2%/}/NewProcessors"
TemporaryProcessorsPath=${5%/}/Processors
TemporaryPluginsPath=${5%/}/Plugins
TemporaryNewProcessorsPath=${5%/}/NewProcessors
TemporaryStorage="${5%/}"

WriteLog "AppPath: ${AppPath}"
WriteLog "ProcessorsPath: ${ProcessorsPath}"
WriteLog "PluginsPath: ${PluginsPath}"
WriteLog "NewProcessorsPath: ${NewProcessorsPath}"
WriteLog "TemporaryProcessorsPath: ${TemporaryProcessorsPath}"
WriteLog "TemporaryPluginsPath: ${TemporaryPluginsPath}"
WriteLog "TemporaryNewProcessorsPath: ${TemporaryNewProcessorsPath}"

#
# --- NEXT, CHECK IF PREVIOUS VERSION OF HOBOWARE PRO EXISTS
#     IF IT DOES, SAVE PLUGINS AND PROCESSORS AND THEN
#     REMOVE THE PREVIOUS HOBOWARE PRO
#
WriteLog "Checking for existing HOBOware application"
if test -e "${AppPath}"
then
	WriteLog "Previous HOBOware exists" 
	PreviousVersion=$(defaults read "${AppPath%/}"/Contents/info CFBundleVersion)
	WriteLog "Previous version: $PreviousVersion" 

# --- IF PROCESSORS FOLDER EXISTS, CHECK FOR OLD HELP AND DELETE
	if test -d "${ProcessorsPath}"
	then
		WriteLog "Existing HOBOware has Processor files"
		WriteLog "Check if old Help folder exists and remove if it does"
		if test -d "${ProcessorsHelpPath}"
		then
			WriteLog "Removing old Processors help files"
			if rm -R "${ProcessorsHelpPath}"
			then
				WriteLog "Old Processors help removed"
			else
				WriteLog "** Error removing old Processors help"
			fi
		else
			WriteLog "No old Processors help found"
		fi
	else
		WriteLog "No previous Processors folder found at ${ProcessorsPath}"
	fi

	if test -e "${PluginsPath}"
	then
		WriteLog "Plugins path found at: ${PluginsPath}"

		if test -e "${ExistingAlarmsTool}"
		then
			if sudo cp -p "${ExistingAlarmsTool}" "${TemporaryStorage}"
			then
				WriteLog "Existing Alarm and Readout Tool copied to ${TemporaryStorage}"
			else
				WriteLog "** Error copying existing Alarm and Readout Tool to ${TemporaryStorage}"
			fi
		else
			WriteLog "No existing Alarm and Readout Tool found"
		fi
	else
		WriteLog "No existing Alarm and Readout Tool found"
	fi
else
	WriteLog "No previous copy of HOBOware found"
fi

WriteLog ""

exit $retval
