#!/bin/bash
# OnsetPostFunctions 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/Library/Application\ Support
#            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) Beware when needing to include the 'space' character or an apostrophe in a
#            file name or path. If the text IS NOT enclosed in double quotes, you need to
#            escape the 'space' or apostophe with a backslash as in these examples:
#
#                         BasePath=~/UnixScriptTests/untitled\ folder/
#                         FirstPath="${BasePath%/}"/UntitledFolder/Jim\'s\ File.txt
#
#            Notice that the FirstPath value encloses the BasePath value in quotes but does
#            not enclose the new part containing the 'space' and apostrophe in quotes. Also
#            note that FirstPath uses trick number 1) to ensure that BasePath ends with a
#            forward slash.
#
#         5) This is not currently used in this script. If you need to get just the filename
#            (or directory name) from the end of a pathname, use the basename external command.
#            And if you need just the directory part of the path, use the dirname external command.
#            Be aware, though, that basename could return any kind of file so you must check whether
#            it is a directory, a regular file or some special file. For instance, if the path is
#            entered as argument 1:
#                    dir=$(dirname "${1}")
#                    file=$(basename "${1}")
#                    echo "Directory only: $dir"
#                    echo "Basename only:  $file"
#                    if [ -d "${1}" ]
#                    then
#                        echo "and is a directory"
#                    elif [ -f "${1}" ]
#                    then
#                        echo "and is a regular file"
#                    else
#                        echo "and is a special type of file"
#                    fi
#
#         6) When there are embedded spaces in the paths or file names when using the "for <file> in $<file list>"
#            command, remember that it defaults to using a space to break up the long list of names. So, we change
#            the IFS (internal field separator) to ':' temporarily (saving the old one in "oldifs" and restoring
#            it later.
#
#         7) The Executable property has been set in Subversion for this file. Make sure it remains
#            that way.
#
#
# -- DEFINE FUNCTIONS USED LATER IN THE SCRIPT
#
# Changes owner and group of file or directory, files and subdirectories
# to the logged-on user and the user's group. Also changes permissions
# to R/W for User and Group but only R for Others.
# Call function with argument of filename or directory name.
function MakeUserOwner {
  local UserGroup
  UserGroup=$(id -gn "$USER")

  # change owner to User and User's Group
  if sudo chown -R "$USER:$UserGroup" "${1}"
  then
    WriteLog "Ownership of ${1} changed to $USER:$UserGroup"
  else
    WriteLog "** Error changing ownership of ${1}"
    return 1
  fi

  # Change permissions to R/W for user and group and R-only for Others
  # Notice that execute permission, X, is capital X, this says, "Make
  # it executable only if it was already executable."
  if sudo chmod -f -R ug+rwX,o=u-w  "${1}"
  then
    WriteLog "Permissions of ${1} changed"
  else
    WriteLog "** Error changing permissions of ${1}"
    return 1
  fi
  return 0
}

#
# Writes debugging information out to HOBOwareInstall.txt file in user's home folder
#
function WriteLog {
  echo "$*"  >> ~/HOBOwareInstall.txt
}

#
#
#   N O T I C E  -   N A M E S   F O R   M A N U A L S
#                    Hopefully these will not change again
#

# User's Guide
ProManual=HOBOware\ User\'s\ Guide\ -\ 12730.pdf
ProManualFr=HOBOware\ User\'s\ Guide-fr\ 12733.pdf

# Getting Started Guide
GettingStartedManual=HOBOware\ Getting\ Started\ Guide\ -\ 12284.pdf
GettingStartedManualFr=HOBOware\ Getting\ Started\ Guide-fr\ 12407.pdf

# Data Assistant Manuals
BCAManual=Barometric\ Compensation\ Assistant\ User\'s\ Guide\ -\ 10572.pdf
BCAManualFr=Barometric\ Compensation\ Assistant\ User\'s\ Guide-fr\ 12398.pdf

GrainsManual=Grains\ Per\ Pound\ Assistant\ User\'s\ Guide\ -\ 10573.pdf
GrainsManualFr=Grains\ Per\ Pound\ Assistant\ User\'s\ Guide-fr\ 12400.pdf

GDDManual=Growing\ Degree\ Days\ Assistant\ User\'s\ Guide\ -\ 10574.pdf
GDDManualFr=Growing\ Degree\ Days\ Assistant\ User\'s\ Guide-fr\ 12399.pdf

KWHManual=kWh\ Assistant\ User\'s\ Guide\ -\ 10571.pdf
KWHManualFr=kWh\ Assistant\ User\'s\ Guide-fr\ 12401.pdf

LinearScalingManual=Linear\ Scaling\ Assistant\ User\'s\ Guide\ -\ 10569.pdf
LinearScalingManualFr=Linear\ Scaling\ Assistant\ User\'s\ Guide-fr\ 12403.pdf

PulseScalingManual=Pulse\ Scaling\ Assistant\ User\'s\ Guide\ -\ 10570.pdf
PulseScalingManualFr=Pulse\ Scaling\ Assistant\ User\'s\ Guide-fr\ 12402.pdf

ConductivityManual=Conductivity\ Assistant\ User\'s\ Guide\ -\ 15019.pdf

DissolvedOxygenManual=Dissolved\ Oxygen\ Assistant\ User\'s\ Guide\ -\ 15604.pdf

AlarmsToolManual=Alarm\ and\ Readout\ Tool\ User\'s\ Guide\ -\ 15015.pdf

#
# Notice, the old manuals (without the Document Numbers) will be removed below
# if they are found in the old <user home>/Documents/HOBOware folder or the
# new <user home>/Library/Application Support/HOBOware folder
#

#
# B E G I N N I N G   O F   S C R I P T
#
WriteLog ""
WriteLog "Running OnsetPostFunctions script"
WriteLog "Parameters:"
let ParamCount=0
for param in "${@}"
do
	let ParamCount=ParamCount+1
	WriteLog "$ParamCount: $param"
done
WriteLog ""

WriteLog "HOBOware installer launched from $1" 
WriteLog "HOBOware installed in $2"
WriteLog "Mountpoint of destination volume is $3"
WriteLog "Root directory for current System folder is $4"
WriteLog "Scratchpad area used by installer at $5"
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

#
# * * *   B E F O R E   F I R S T   * * *
#
#
# --- Check if HOBOware.app exists
#
if test -e "${2%/}/HOBOware.app"
then
	WriteLog "HOBOware.app found where it is supposed to be"
else
	WriteLog "** Error - HOBOware.app was not installed!"
	let retval=96
	exit $retval	
fi

#
# --- FIRST, CHECK IF PREVIOUS EXTENSION EXISTS AND REMOVE IT
#
# test if /System/Library/Extensions/HOBOkext.kext exists and 
# if it does exist, unload it and remove it
if test -e /System/Library/Extensions/HOBOkext.kext ; then
   WriteLog "Previous HOBOkext.kext exists" 

#  Attempt to remove the Kernel Extension
   if sudo rm -f -R /System/Library/Extensions/HOBOkext.kext  ; then
      WriteLog "Previous HOBOkext.kext removed" >>  ~/HOBOwareInstall.txt
   else
      WriteLog "** Error removing previous HOBOkext.kext" ;
      let retval=96
   fi
else
   WriteLog "No previous HOBOkext found" ;
fi

#
# --- SECOND, MOVE NEW EXTENSION TO EXTENSIONS FOLDER
#
# create full path to where the kernel extension was stored temporarily
KextTempPath=${2%/}/HOBOkext.kext
WriteLog "KextTempPath: ${KextTempPath}"
# copy kernel extension from Applications folder to Extensions folder
if sudo cp -f -p -R "${KextTempPath}" /System/Library/Extensions ; then
   WriteLog "New HOBOkext.kext copied to Extensions folder" ;
else
   WriteLog "** Error copying new HOBOkext.kext to Extensions folder" ;
   let retval=96
fi

# remove kernel extension from Applications folder 
if sudo rm -f -R "${KextTempPath}" ; then
   WriteLog "New HOBOkext.kext removed from temporary location" ;
else
   WriteLog "** Error removing new HOBOkext.kext temporary folder" ;
fi

#
# --- THIRD, CHANGE OWNER, GROUP AND PERMISSIONS OF NEW EXTENSION
#
# change owner to root
if sudo chown -R root /System/Library/Extensions/HOBOkext.kext ; then
   WriteLog "Ownership of new HOBOkext.kext changed to root" ;
else
   WriteLog "** Error changing ownership of new HOBOkext.kext" ;
   let retval=96
fi

# change group to wheel
if sudo chgrp -R wheel /System/Library/Extensions/HOBOkext.kext ; then
   WriteLog "Group of new HOBOkext.kext changed to wheel" ;
else
   WriteLog "** Error changing group of new HOBOkext.kext" ;
   let retval=96
fi

# change permissions to drwxr-x-r-x
if sudo chmod -R go-w /System/Library/Extensions/HOBOkext.kext ; then
   WriteLog "Permissions of new HOBOkext.kext changed to drwxr-xr-x" ;
else
   WriteLog "** Error changing permissions of new HOBOkext.kext" ;
   let retval=96
fi


#
# --- FOURTH, TOUCH THE EXTENSION TO UPDATE ITS DATE AND TIME
#
if sudo touch /System/Library/Extensions/HOBOkext.kext ; then
   WriteLog "New HOBOkext.kext access and modification times updated";
else
   WriteLog "** Error updating access and modification times of new HOBOkext.kext";
fi

#
# USE KEXTSTAT TO MAKE SURE KEXT IS REALLY RUNNING - this doesn't work anymore, don't use
#
#if kextstat | grep -q 'HOBOkext' ; then
#	WriteLog "HOBOkext found in kextstat output"
#else
#	WriteLog "HOBOkext NOT found in kextstat ouput"
#fi

#
# --- COPY THE COM PORT JNI LIB TO ITS PROPER PLACE
# create full path to where the kernel extension was stored temporarily
CommJNILibTempPath=${2%/}/libjspMacOSX.jnilib
WriteLog "CommJNILibTempPath: ${CommJNILibTempPath}"
# move library from Applications folder to Java Extensions folder
if sudo mv -f "${CommJNILibTempPath}" /Library/Java/Extensions ; then
   WriteLog "Comm port library moved to /Library/Java/Extensions folder" ;
else
   WriteLog "** Error moving comm port library to /Library/Java/Extensions folder" ;
   let retval=96
fi

#
# -- MOVE SAMPLE DATAFILES TO LIBRARY/APPLICATION SUPPORT FOLDER IN USER'S AREA
#
NewHOBOwareFolderInUserDocuments=~/Documents/HOBOware
OldHOBOwareFolderInUserDocuments=~/Library/Application\ Support/HOBOware
TemporarySamplesFolder="${2%/}/SampleHOBODatafiles"
TemporaryConfigsPath="${TemporarySamplesFolder%/}/Configs"
TemporaryFWUpdatesPath="${2%/}/FWUpdates"
TemporaryManualPath="${2%/}/${ProManual}"
TemporaryManualPathFr="${2%/}/${ProManualFr}"
TemporaryQuickStartPath="${2%/}/${GettingStartedManual}"
TemporaryQuickStartPathFr="${2%/}/${GettingStartedManualFr}"
TemporaryProgramTypeTxtPath="${2%/}/programtype.txt"
ManualsFolderPath="${NewHOBOwareFolderInUserDocuments%/}/Manuals"
FirmwareUpdatesFolderPath="${NewHOBOwareFolderInUserDocuments%/}/FWUpdates"
SampleDatafilesFolderPath="${NewHOBOwareFolderInUserDocuments%/}/Sample Datafiles"
ConfigsFolderPath="${NewHOBOwareFolderInUserDocuments%/}/Configs"
OldConfigsFolderPath="${OldHOBOwareFolderInUserDocuments%/}/Configs"

#
# N E W - Look for old manuals (no document numbers) and remove them if found
#
OldManualsToRemove="HOBOware Getting Started Guide.pdf:HOBOware Getting Started Guide-fr.pdf:HOBOware User's Guide.pdf:HOBOware User's Guide-fr.pdf:Barometric Compensation Assistant User's Guide.pdf:Barometric Compensation Assistant User's Guide-fr.pdf:Grains Per Pound Assistant User's Guide.pdf:Grains Per Pound Assistant User's Guide-fr.pdf:Growing Degree Days Assistant User's Guide.pdf:Growing Degree Days Assistant User's Guide-fr.pdf:kWh Assistant User's Guide.pdf:kWh Assistant User's Guide-fr.pdf:Linear Scaling Assistant User's Guide.pdf:Linear Scaling Assistant User's Guide-fr.pdf:Pulse Scaling Assistant User's Guide.pdf:Pulse Scaling Assistant User's Guide-fr.pdf"

ManualsToRemoveInOldLocation="Alarm and Readout Tool User's Guide - 15015.pdf:Barometric Compensation Assistant User's Guide - 10572.pdf:Conductivity Assistant User's Guide - 15019.pdf:Grains Per Pound Assistant User's Guide - 10573.pdf:Growing Degree Days Assistant User's Guide - 10574.pdf:HOBOnode Setup Guide 13542.pdf:HOBOware Getting Started Guide - 12284.pdf:HOBOware User's Guide - 12730.pdf:kWh Assistant User's Guide - 10571.pdf:Linear Scaling Assistant User's Guide - 10569.pdf:Pulse Scaling Assistant User's Guide - 10570.pdf"

FrenchManualsToRemoveInOldLocation="HOBOware User's Guide-fr 12733.pdf:HOBOware Getting Started Guide-fr 12407.pdf:HOBOnode Setup Guide-fr 13827.pdf:Barometric Compensation Assistant User's Guide-fr 12398.pdf:Grains Per Pound Assistant User's Guide-fr 12400.pdf:Growing Degree Days Assistant User's Guide-fr 12399.pdf:kWh Assistant User's Guide-fr 12401.pdf:Linear Scaling Assistant User's Guide-fr 12403.pdf
Pulse Scaling Assistant User's Guide-fr 12402.pdf"

SamplesToRemoveInOldLocation="24 Hour Room Profile.hobo:24-hr Weather Data.dtf:Home_Energy_Audit.dtf:Ocean Buoy Station.hproj:Office_Temperature_corrupt.hsec:Office_Temperature.hsec:Refrigerator Door.hobo:Waquoit_Weather_Station.hproj:Weather Data for Import.txt:Well_Log_Baro.hobo:Well_Log_Downwell.hobo:Well_Log.hproj"

oldifs="$IFS"
IFS=:
for manual in $OldManualsToRemove
do
	# First, check where manuals used to be: <user home>/Library/Application Support/HOBOware
	if [ -e "$OldHOBOwareFolderInUserDocuments/$manual" ]
	then
		if rm "$OldHOBOwareFolderInUserDocuments/$manual"
		then
			WriteLog "Removed old manual: $OldHOBOwareFolderInUserDocuments/$manual"
		else
			WriteLog "Could not remove old manual: $OldHOBOwareFolderInUserDocuments/$manual"
		fi
	fi

	# Second, check where manuals are now saved: <user home>/Documents/HOBOware
	if [ -e "$NewHOBOwareFolderInUserDocuments/$manual" ]
	then
		if rm "$NewHOBOwareFolderInUserDocuments/$manual"
		then
			WriteLog "Removed old manual: $NewHOBOwareFolderInUserDocuments/$manual"
		else
			WriteLog "Could not remove old manual: $NewHOBOwareFolderInUserDocuments/$manual"
		fi
	fi
done

#
# NEW - Remove manuals in old location
#
WriteLog "Look for copies of manuals in $OldHOBOwareFolderInUserDocuments and remove them" 
for manual in $ManualsToRemoveInOldLocation
do
	# Check in old location: <user home>/Library/Application Support/HOBOware
	if [ -e "$OldHOBOwareFolderInUserDocuments/$manual" ]
	then
		if rm "$OldHOBOwareFolderInUserDocuments/$manual"
		then
			WriteLog "Removed manual in old location: $OldHOBOwareFolderInUserDocuments/$manual"
		else
			WriteLog "Could not remove manual in old location: $OldHOBOwareFolderInUserDocuments/$manual"
		fi
	fi
done

#
# NEW - Remove French manuals in old location
#
WriteLog "Look for copies of French manuals in $OldHOBOwareFolderInUserDocuments and remove them" 
for manual in $FrenchManualsToRemoveInOldLocation
do
	# Check in old location: <user home>/Library/Application Support/HOBOware
	if [ -e "$OldHOBOwareFolderInUserDocuments/$manual" ]
	then
		if rm "$OldHOBOwareFolderInUserDocuments/$manual"
		then
			WriteLog "Removed French manual in old location: $OldHOBOwareFolderInUserDocuments/$manual"
		else
			WriteLog "Could not remove French manual in old location: $OldHOBOwareFolderInUserDocuments/$manual"
		fi
	fi
done

#
# NEW - Remove Sample Datafiles in old location
#
WriteLog "Look for copies of Sample Datafile in $OldHOBOwareFolderInUserDocuments and remove them" 
for datafile in $SamplesToRemoveInOldLocation
do
	# Check in old location: <user home>/Library/Application Support/HOBOware
	if [ -e "$OldHOBOwareFolderInUserDocuments/$datafile" ]
	then
		if rm "$OldHOBOwareFolderInUserDocuments/$datafile"
		then
			WriteLog "Removed sample datafile in old location: $OldHOBOwareFolderInUserDocuments/$datafile"
		else
			WriteLog "Could not remove sample datafile in old location: $OldHOBOwareFolderInUserDocuments/$datafile"
		fi
	fi
done

IFS="$oldifs"

WriteLog "Install sample datafiles from this temporary folder: ${TemporarySamplesFolder}"
WriteLog "Install configurations from this temporary folder: ${TemporaryConfigsFolder}"
WriteLog "Install English manual from this temporary folder: ${TemporaryManualPath}"
WriteLog "Install French manual from this temporary folder: ${TemporaryManualPathFr}"
WriteLog "Install English Quick Start from this temporary folder: ${TemporaryQuickStartPath}"
WriteLog "Install French Quick Start from this temporary folder: ${TemporaryQuickStartPathFr}"
WriteLog "Install Program Update Type file from this temporary folder: ${TemporaryProgramTypeTxtPath}"
WriteLog "Install these to HOBOware folder: ${NewHOBOwareFolderInUserDocuments}"

# check if HOBOware folder already exists, if it does not, create it
if test -d "${NewHOBOwareFolderInUserDocuments}"
then
  WriteLog "${NewHOBOwareFolderInUserDocuments} exists"
else
  if sudo mkdir "${NewHOBOwareFolderInUserDocuments}" ; then
    WriteLog "Created folder ${NewHOBOwareFolderInUserDocuments}"
  else
    WriteLog "** Error creating folder ${NewHOBOwareFolderInUserDocuments}"
	let retval=96
	exit $retval
  fi
fi

#
# N E W  -  M O V E   E N T I R E   H O B O W A R E   F O L D E R   F R O M   O L D   L O C A T I O N
#           I N   " L I B R A R Y / A P P L I C A T I O N   S U P P O R T "   T O   N E W   L O C A T I O N
#           I N   " D O C U M E N T S "
#

# If old HOBOware folder exists, copy it to new location in user Documents and then delete old HOBOware folder
#
if test -d "${OldHOBOwareFolderInUserDocuments}"
then
  WriteLog "Old HOBOware folder exists at ${OldHOBOwareFolderInUserDocuments}"
  WriteLog "Copy old HOBOware folder to new location at ${NewHOBOwareFolderInUserDocuments}"  
  if sudo cp -f -p -R "${OldHOBOwareFolderInUserDocuments}"/* "${NewHOBOwareFolderInUserDocuments}"
  then
    WriteLog "Old HOBOware folder successfully copied to new location"
	WriteLog "Remove old HOBOWare folder contents"
	if sudo rm -f -R "${OldHOBOwareFolderInUserDocuments}"/*
	then
	  WriteLog "Old HOBOware folder contents successfully removed"
          # need to remove the .DS_Store files separately
          sudo find "${OldHOBOwareFolderInUserDocuments}" -name '.DS_Store' -type f -delete
	else
	  WriteLog "** Error removing old HOBOware folder contents (may just be empty)"
	fi
  else
    WriteLog "** Error copying olf HOBOware folder (may just be empty)"
  fi
  
  # now remove old HOBOware folder
  WriteLog "Removing old HOBOware folder"
  if sudo rmdir "${OldHOBOwareFolderInUserDocuments}"
  then
    WriteLog "Old HOBOware folder removed"
  else
    WriteLog "** Error removing old HOBOware folder: ${OldHOBOwareFolderInUserDocuments} error = $?"
  fi
else
  WriteLog "No old HOBOware folder found at ${OldHOBOwareFolderInUserDocuments}"
fi
  
# make the current user the owner of the HOBOware folder in Documents
if MakeUserOwner "${NewHOBOwareFolderInUserDocuments}"
then
  WriteLog "Ownership of ${NewHOBOwareFolderInUserDocuments} changed to $USER"
else
  WriteLog "** Error changing ownership of ${NewHOBOwareFolderInUserDocuments}, error = $?"
fi

# check if Manuals folder already exists, if it does not, create it
if test -d "${ManualsFolderPath}"
then
  WriteLog "${ManualsFolderPath} exists"
else
  if sudo mkdir "${ManualsFolderPath}" ; then
    WriteLog "Created folder ${ManualsFolderPath}"
  else
    WriteLog "** Error creating folder ${ManualsFolderPath}"
  fi
fi

# ** NEW ** - make the current user the owner of the Manuals folder in Documents
if MakeUserOwner "${ManualsFolderPath}"
then
  WriteLog "Ownership of ${ManualsFolderPath} changed to $USER"
else
  WriteLog "** Error changing ownership of ${ManualsFolderPath}, error = $?"
fi

# check if Sample Datafiles folder already exists, if it does not, create it
if test -d "${SampleDatafilesFolderPath}"
then
  WriteLog "${SampleDatafilesFolderPath} exists"
else
  if sudo mkdir "${SampleDatafilesFolderPath}" ; then
    WriteLog "Created folder ${SampleDatafilesFolderPath}"
  else
    WriteLog "** Error creating folder ${SampleDatafilesFolderPath}"
  fi
fi

# check if Configs folder already exists, if it does not, create it
if test -d "${ConfigsFolderPath}"
then
  WriteLog "${ConfigsFolderPath} exists"
else
  if sudo mkdir "${ConfigsFolderPath}" ; then
    WriteLog "Created folder ${ConfigsFolderPath}"
  else
    WriteLog "** Error creating folder ${ConfigsFolderPath}"
  fi
fi

# check if Firmware Updates folder, FWUpdates, already exists, if it does not, create it
if test -d "${FirmwareUpdatesFolderPath}"
then
  WriteLog "${FirmwareUpdatesFolderPath} exists"
else
  if sudo mkdir "${FirmwareUpdatesFolderPath}" ; then
    WriteLog "Created folder ${FirmwareUpdatesFolderPath}"
  else
    WriteLog "** Error creating folder ${FirmwareUpdatesFolderPath}"
  fi
fi

# NO LONGER NEEDED - this is done after any firmware files are copied into this folder
# make the current user the owner of the FWUpdates folder in Documents
#if MakeUserOwner "${FirmwareUpdatesFolderPath}"
#then
#  WriteLog "Ownership of ${FirmwareUpdatesFolderPath} changed to $USER"
#else
#  WriteLog "** Error changing ownership of ${FirmwareUpdatesFolderPath}, error = $?"
#fi

#
# If programtype.txt exists, copy it to user's Library/Applications Support/HOBOware folder
#
ProgramTypeFinalPath="${2%/}/HOBOware.app/Contents/Resources/Java"
if [ "${TemporaryProgramTypeTxtPath}" = "" ]
then
  WriteLog "** Path for program type file is blank"
  let retval=96
fi
if test -f "${TemporaryProgramTypeTxtPath}"
then
  if sudo mv -f "${TemporaryProgramTypeTxtPath}" "${ProgramTypeFinalPath}"
  then
    WriteLog "HOBOware update type file successfully moved to ${ProgramTypeFinalPath}"
  else
    WriteLog "** Error moving HOBOware update type file to ${ProgramTypeFinalPath}"
  fi
else
    WriteLog "No HOBOware update type file file found at ${TemporaryProgramTypeTxtPath}"
fi

# samples folder should exist now, if it does, move samples there
if test -d "${SampleDatafilesFolderPath}"
then
  # Copy temporary samples folder contents to Documents/HOBOware
  # Notice using /* after TemporarySamplesFolder to get individual file names
  # and the wildcard part is outside the double quotes.
  # We use the 'f' option to overwrite existing files
  # We use the 'p' option to preserve file times and file flags and file mode 
  # NOTICE - we no longer use the -R recursive flag because Configs should not be copied yet
  if sudo cp -f -p "${TemporarySamplesFolder}"/*.* "${SampleDatafilesFolderPath}"
  then
    WriteLog "Sample datafiles copied to ${SampleDatafilesFolderPath}"
    # set ownership of all sample files to user
    if MakeUserOwner "${SampleDatafilesFolderPath}"
    then
      WriteLog "Ownership of Samples folder changed to $USER"
    else
      WriteLog "** Error changing ownership of Samples folder, error = $?"
    fi
  else
    WriteLog "** Error copying sample datafiles to $SampleDatafilesFolderPath, error = $?"
  fi
fi
 
# Copy temporary configs folder contents to Documents/HOBOware
# Notice using /* after TemporaryConfigsPath to get individual file names
# Also notice that the wildcard part is outside the double quotes.
# Also also notice that we use the 'f' option to overwrite existing files 
if sudo cp -f -p "${TemporaryConfigsPath%/}"/* "${ConfigsFolderPath}"
then
  WriteLog "Configuration copied to ${ConfigsFolderPath}"
  # set ownership of all configurations to user
  if MakeUserOwner "${ConfigsFolderPath}"
  then
    WriteLog "Ownership of Configs folder changed to $USER"
  else
    WriteLog "** Error changing ownership of Configs folder"
  fi
else
  WriteLog "** Error copying configurations to $ConfigsFolderPath"
fi

# Copy contents of TemporaryFWUpdatesPath folder contents to 
# folder FirmwareUpdatesFolderPath. Notice this is NOT using /* after
# TemporaryFWUpdatesPath so there will be no error if the directory at
# TemporaryFWUpdatesPath is empty.
# Also also notice that we use the 'f' option to overwrite existing files.
# Also notice we are using -R becuase the source is a folder but this will
# also get any subfolders and copy them to the destination. 
if sudo cp -R -f -p "${TemporaryFWUpdatesPath%/}"/ "${FirmwareUpdatesFolderPath}"
then
  WriteLog "Firmware Updates copied to ${FirmwareUpdatesFolderPath}"
else
  WriteLog "** Error copying firmware updates to $FirmwareUpdatesFolderPath"
fi

# Set ownership of all firmware files to user (even if none were copied - we
# at least want to make sure this folder is owned by the user.
if MakeUserOwner "${FirmwareUpdatesFolderPath}"
then
    WriteLog "Ownership of FWUpdates folder changed to $USER"
else
    WriteLog "** Error changing ownership of FWUpdates folder to $USER"
fi

#
# Remove temporary sample datafiles, configs and firmware updates folders no matter what
#
if sudo rm -f -R "${TemporarySamplesFolder}"
then
  WriteLog "Temporary sample datafiles folder removed"
else
  WriteLog "** Error removing temporary sample datafiles folder"
fi

if sudo rm -f -R "${TemporaryConfigsPath}"
then
  WriteLog "Temporary configs folder removed"
else
  WriteLog "** Error removing temporary configs folder"
fi

if sudo rm -f -R "${TemporaryFWUpdatesPath}"
then
  WriteLog "Temporary firmware updates folder removed"
else
  WriteLog "** Error removing temporary firmware updates folder"
fi

#
# These configuration files must be deleted if they exist, added 02AUG2011 jed for v3.2.2
# Notice the -f option. It will not show a prompt and will not error if the file does not exist.
#
rm -f "${ConfigsFolderPath%/}"/T-CDI-5200-20S.hcfg
rm -f "${ConfigsFolderPath%/}"/T-CDI-5200-20S-U30.hcfg

#
# If manual file exists, copy it to user's Documents/HOBOware folder
#

if test -f "${TemporaryManualPath}"
then
  if sudo mv -f "${TemporaryManualPath}" "${ManualsFolderPath}"
  then
    WriteLog "HOBOware manual successfully moved to ${ManualsFolderPath}"
  else
    WriteLog "** Error moving HOBOware manual to ${ManualsFolderPath}"
  fi
else
    WriteLog "No HOBOware manual file found at ${TemporaryManualPath}"
fi

#
# If French manual file exists, copy it to user's Documents/HOBOware folder
#

if test -f "${TemporaryManualPathFr}"
then
  if sudo mv -f "${TemporaryManualPathFr}" "${ManualsFolderPath}"
  then
    WriteLog "French manual successfully moved to ${ManualsFolderPath}"
  else
    WriteLog "** Error moving French manual to ${ManualsFolderPath}"
  fi
else
    WriteLog "No French manual file found at ${TemporaryManualPathFr}"
fi

#
# If quick start file exists, copy it to user's Documents/HOBOware folder
#
if test -f "${TemporaryQuickStartPath}"
then
  if sudo mv -f "${TemporaryQuickStartPath}" "${ManualsFolderPath}"
  then
    WriteLog "Quick Start successfully moved to ${ManualsFolderPath}"
  else
    WriteLog "** Error moving Quick Start to ${ManualsFolderPath}"
  fi
else
    WriteLog "No Quick Start file found at ${TemporaryQuickStartPath}"
fi

#
# If French quick start file exists, copy it to user's Documents/HOBOware folder
#
if test -f "${TemporaryQuickStartPathFr}"
then
  if sudo mv -f "${TemporaryQuickStartPathFr}" "${ManualsFolderPath}"
  then
    WriteLog "French Quick Start successfully moved to ${ManualsFolderPath}"
  else
    WriteLog "** Error moving French Quick Start to ${ManualsFolderPath}"
  fi
else
    WriteLog "No French Quick Start file found at ${TemporaryQuickStartPathFr}"
fi

oldifs="$IFS"
IFS=:
DataAssistantManualList="${BCAManual}:${GrainsManual}:${GDDManual}:${KWHManual}:${LinearScalingManual}:${PulseScalingManual}:${ConductivityManual}:${DissolvedOxygenManual}"
WriteLog "Copying English Data Assistant manuals to ${ManualsFolderPath}"
for DAManual in ${DataAssistantManualList}
do
#	WriteLog "Checking for ${DAManual}"
	if [ -e "${2%/}/${DAManual}" ]
	then
		if sudo mv -f "${2%/}/${DAManual}" "${ManualsFolderPath}"
		then
			WriteLog "Moved English data assistant manual: ${DAManual}"
		else
			WriteLog "Could not move: ${DAManual}"
		fi
	fi
done

DataAssistantManualListFr="${BCAManualFr}:${GrainsManualFr}:${GDDManualFr}:${KWHManualFr}:${LinearScalingManualFr}:${PulseScalingManualFr}"
WriteLog "Copying French Data Assistant manuals to ${ManualsFolderPath}"
for DAManual in ${DataAssistantManualListFr}
do
#	WriteLog "Checking for ${DAManual}"
	if [ -e "${2%/}/${DAManual}" ]
	then
		if sudo mv -f "${2%/}/${DAManual}" "${ManualsFolderPath}"
		then
			WriteLog "Moved French data assistant manual: ${DAManual}"
		else
			WriteLog "Could not move: ${DAManual}"
		fi
	fi
done
IFS="$oldifs"

#
# --- Move Alarm and Readout Tool manual
#
if [ -e "${2%/}/${AlarmsToolManual}" ]
then
    if sudo mv -f "${2%/}/${AlarmsToolManual}" "${ManualsFolderPath}"
    then
        WriteLog "Moved Alarms Tool manual: ${AlarmsToolManual}"
    else
        WriteLog "Could not move Alarms Tool manual: ${AlarmsToolManual}"
    fi
fi

#
# --- IF TEMPORARY PLUGINS AND PROCESSORS FOLDERS EXIST, RESTORE THEM - now only restore Alarm and Readout Tool
AppPath=${2%/}/HOBOware.app
ProcessorsPath="${AppPath}/Contents/Resources/Java"
CompleteProcessorsPath="${ProcessorsPath}/Processors"
PluginsPath="${AppPath}/Contents/Resources/Java"
CompletePluginsPath="${PluginsPath}/Plugins"
NewProcessorsPath="${2%/}/NewProcessors"

WriteLog "AppPath: ${AppPath}"
WriteLog "ProcessorsPath: ${ProcessorsPath}"
WriteLog "CompleteProcessorsPath: ${CompleteProcessorsPath}"
WriteLog "NewProcessorsPath: ${NewProcessorsPath}"

#
# --- Check if HOBOware.app exists
#
if test -e "${AppPath}"
then
	WriteLog "HOBOware.app found where it is supposed to be"
else
	WriteLog "** Error - HOBOware.app does not exist!"
	let retval=96
fi
	
#
# Look for nested Processors or Plugins folder inside the top-level Processors and Plugins folders
#       and delete the nested versions without deleting the post-processors and plugins.
#
NestedProcessors="${CompleteProcessorsPath}/Processors"
NestedPlugins="${CompletePluginsPath}/Plugins"
if test -d "${NestedProcessors}"
then
	WriteLog "Nested Processors folders found - attempting to remove"
	if sudo rm -fR "${NestedProcessors}"
	then
		WriteLog "Nested Processors folders removed successfully"
	else
		WriteLog "** Error removing nested Processors folders"
	fi
else
	WriteLog "No nested Processors folders found"	
fi

if test -d "${NestedPlugins}"
then
	WriteLog "Nested Plugins folders found - attempting to remove"
	if sudo rm -fR "${NestedPlugins}"
	then
		WriteLog "Nested Plugins folders removed successfully"
	else
		WriteLog "** Error removing nested Plugins folders"
	fi
else
	WriteLog "No nested Plugins folders found"
fi


#
# --- Install free post-processors every time
#
FreeProcessors="Depth.jar kWh.jar LinearScaling.jar PulseScaling.jar Conductivity.jar Grains.jar DegreeDay.jar DissolvedOxygen.jar"

if test -d "${NewProcessorsPath}"
then
    WriteLog "New post-processors folder found at ${NewProcessorsPath}"

    # Install any free post-processors
    WriteLog "Install any free processors"
    for Processor in $FreeProcessors
    do
        if test -f "${NewProcessorsPath}/$Processor"
        then
            if sudo cp -f -p "${NewProcessorsPath}/$Processor" "${CompleteProcessorsPath}"
            then
                WriteLog "$Processor processor loaded"
            else
                WriteLog "** Error loading $Processor processor"
            fi
        fi
    done

    # Remove NewProcessors folder now that we're done with it
    if sudo rm -f -R "${NewProcessorsPath}"
    then
        WriteLog "Removed new processors folder"
    else
        WriteLog "** Error removing new processors folder"
    fi
else
    WriteLog "New post-processors not found at ${NewProcessorsPath}"
fi

#
# --- Restore original Alarm and Readout Tool if it exists
#
TemporaryAlarmsTool="${5%/}/AlarmsTool.jar"

if test -e "${TemporaryAlarmsTool}"
then
  WriteLog "Creating new Alarms folder: ${CompletePluginsPath%/}/Alarms"
  if sudo mkdir -p "${CompletePluginsPath%/}/Alarms"
  then
    WriteLog "Restoring existing Alarm and Readout Tool from ${TemporaryAlarmsTool} to ${CompletePluginsPath%/}/Alarms"
    if sudo cp -f -p "${TemporaryAlarmsTool}" "${CompletePluginsPath%/}/Alarms"
    then
      WriteLog "Existing Alarm and Readout Tool restored"
    else
      WriteLog "** Error restoring existing Alarm and Readout Tool"
    fi
  else
    WriteLog "** Error creating directory for restoring existing Alarm and Readout Tool"
  fi
else
  WriteLog "No Alarms Tool found in temporary storage"
fi


#
# CHANGE OWNER, GROUP AND PERMISSIONS OF JAVA FOLDER AND SUBFOLDERS
# DO THIS FOR ENTIRE APP
#
if MakeUserOwner "${AppPath}"
then
   WriteLog "Ownership of HOBOware.app changed to $USER"
else
   WriteLog "** Error changing ownership of HOBOware.app"
fi

#
# --- Some old versions of HOBOware left manuals in the applications folder. 
#     Remove them here.
#
#     NOTE - This is different from our removing old versions of manuals that
#            we might find in <user home>/Documents/HOBOware or
#            in <user home>/Library/Application Support/HOBOware in code above.
#
if [ -e "/Applications/HOBOware Pro User's Guide Mac.pdf" ]
then
  if sudo rm -f "/Applications/HOBOware Pro User's Guide Mac.pdf"
  then
    WriteLog "HOBOware Pro User's Guide Mac.pdf found and removed from Applications folder"
  else
    WriteLog "** Error - HOBOware Pro User's Guide Mac.pdf found but could not be removed"
  fi
fi

if [ -e "/Applications/HOBOware Getting Started Guide.pdf" ]
then
  if sudo rm -f "/Applications/HOBOware Getting Started Guide.pdf"
  then
    WriteLog "HOBOware Getting Started Guide.pdf found and removed from Applications folder"
  else
    WriteLog "** Error - HOBOware Getting Started Guide.pdf found but could not be removed"
  fi
fi



WriteLog "End installation script"
WriteLog ""


exit $retval
