#!/bin/bash
# OnsetPostFunctions for HOBOware Lite 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) 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
#

#
# -- 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    F O R   M A N U A L 
#                    Hopefully this won't change again
#
LiteManual=HOBOware\ Lite\ User\'s\ Guide\ Mac.pdf


#
# 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 Lite installer launched from $1" 
WriteLog "HOBOware Lite 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

#
# --- FIRST, CHECK IF PREVIOUS EXTENSION EXISTS AND REMOVE IT
#
# test if /System/Library/Extensions/HOBOkext.kext exists and 
# if it does exist, 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

#
# --- NEW --- USE KEXTSTAT TO MAKE SURE KEXT IS REALLY RUNNING
#
#if kextstat | grep -q 'HOBOkext' ; then
#	WriteLog "HOBOkext found in kextstat output"
#else
#	WriteLog "HOBOkext NOT found in kextstat output"
#fi

#
# --- ASK IF USER WANTS TO PLACE ALIAS FOR HOBOWARE LITE ON DESKTOP
#     AND MAKE THE ALIAS IF THAT IS WHAT THEY WANT
#
#ApplicationPath=${2%/}/HOBOwareLite.app
#UserDesktopPath=~/Desktop
#WriteLog "ApplicationPath: ${ApplicationPath}"
#WriteLog "User Desktop folder should be at: ${UserDesktopPath}"

#if "${1%/}/Contents/Resources/InstallOptions.app/Contents/MacOS/JavaApplicationStub"
#then
#  WriteLog "Request to place alias for HOBOware Lite on desktop"
#  if test -d "${UserDesktopPath}" ; then
#    if sudo ln -s -f "${ApplicationPath}" "${UserDesktopPath}" ; then
#      WriteLog "Alias for HOBOware Lite placed on user's desktop" ;
#    else
#      WriteLog "** Error placing alias for HOBOware Lite on desktop" ;
#    fi
#  else
#    WriteLog "** Error, Desktop folder not found"
#  fi
#else
#  WriteLog "User elected to NOT place alias for HOBOware Lite on desktop" ;
#fi

#
# -- MOVE SAMPLE DATAFILES TO DOCUMENTS FOLDER IN USER'S AREA
#
#SamplesPath=~/Documents/HOBOware
HOBOwareFolderInUserDocuments=~/Documents/HOBOware
TemporarySamplesFolder=${2%/}/SampleHOBODatafiles
TemporaryManualPath="${2%/}/${LiteManual}"
WriteLog "Move sample datafiles from this temporary folder: ${TemporarySamplesFolder}"
WriteLog "Move sample datafiles to HOBOware folder: ${HOBOwareFolderInUserDocuments}"
WriteLog "Move manual from this temporary folder: ${TemporaryManualPath}"
WriteLog "Move manual to HOBOware folder: ${HOBOwareFolderInUserDocuments}"

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

# samples folder should exist now, if it does, move samples there
if test -d "${HOBOwareFolderInUserDocuments}" ; then
  # Copy temporary samples folder contents to Documents/HOBOware
  # Notice using /* after TemporarySamplesFolder 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 -R "${TemporarySamplesFolder}"/* "${HOBOwareFolderInUserDocuments}"
  then
    WriteLog "Sample datafiles copied to ${HOBOwareFolderInUserDocuments}"
  else
    WriteLog "** Error copying sample datafiles to $HOBOwareFolderInUserDocuments"
  fi
  # set ownership of all sample files to user
  if MakeUserOwner "${HOBOwareFolderInUserDocuments}"
  then
     WriteLog "Ownership of Samples folder changed to $USER" ;
  else
     WriteLog "** Error changing ownership of Samples folder" ;
  fi
fi

# Remove temporary sample datafiles folder 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 manual file exists, copy it to user's Documents/HOBOware folder
#

if test -f "${TemporaryManualPath}"
then
  if sudo mv -f "${TemporaryManualPath}" "${HOBOwareFolderInUserDocuments}"
  then
    WriteLog "Manual successfully moved to ${HOBOwareFolderInUserDocuments}"
  else
    WriteLog "** Error moving manual to ${HOBOwareFolderInUserDocuments}"
  fi
fi

#
# --- Check if HOBOwareLite.app exists
#
AppPath=${2%/}/HOBOwareLite.app

WriteLog "AppPath: ${AppPath}"
if test -e "${AppPath}"
then
	WriteLog "HOBOwareLite.app does exist where it is supposed to be"
else
	WriteLog "** Error - HOBOwareLite.app does not exist!"
	let retval=96
fi
	


#
# --- NEW --- CHANGE OWNER, GROUP AND PERMISSIONS OF JAVA FOLDER AND SUBFOLDERS
# --- CHANGE - DO THIS FOR ENTIRE APP
#
# make path for Java folder
#JavaPath=${2%/}/HOBOwareLite.app/Contents/Resources/Java
# make sure file is owned by user
#if MakeUserOwner "${JavaPath}"
#then
#   WriteLog "Ownership of Java folder changed to $USER" ;
#else
#   WriteLog "** Error changing ownership of Java folder" ;
#fi
if MakeUserOwner "${AppPath}"
then
   WriteLog "Ownership of HOBOwareLite.app changed to $USER" ;
else
   WriteLog "** Error changing ownership of HOBOwareLite.app" ;
fi

WriteLog "End installation script"
WriteLog ""


exit $retval
