#!/bin/bash

echo "==============================================="
echo "Entered Postflight Script"
echo "*************************"

# Find location of this script in the package installer
# so we know where all the other scripts are located.

MYLOCATION="${PWD}/${BASH_ARGV[0]}"
export MYLOCATION="${MYLOCATION%/*}"
scriptDir=$MYLOCATION


# Run script to create com.apple.Boot.plist
# and pass it the installer destination.

"$scriptDir"BuildBootOptions.sh "${3}"


# Has the temporary directory /.Chameleon/Extra been created?
# If yes then check first for an existing /Extra folder on the
# destination and if exists then back it up and delete existing.
# Then transfer temporary Extra folder to destination.
 
if [ -d "${3}"/.Chameleon/Extra ]; then

	# Check to see if install to EFI system partition was selected
	# if chosen, the package installer would have added a file named
	# 'nullESP' in to the temporary directory /.Chameleon

	# We also need to check to see if the user selected both the
	# standard install and EFI system partition options.
	# If they did then the EFI system partition script would
	# have been cancelled, meaning the Extra folder needs to 
	# be copied the selected destination.

	if [ -f ${3}/.Chameleon/nullESP ] && ! [ -f ${3}/.Chameleon/nullstandard ]; then

		# Does an /Extra folder already exist at the target location?
		# If yes, then make a backup of it

		if [ -d "/Volumes/EFI/Extra" ]; then
			echo "DEBUG: Executing command: Backing up existing /Volumes/EFI/Extra"
			mkdir -p "/Volumes/EFI/ExtraBackup"
			cp -f -R "/Volumes/EFI/Extra" "/Volumes/EFI/ExtraBackup"
			rm -f -R "/Volumes/EFI/Extra"
		fi

		echo "Executing command: ditto ${3}/.Chameleon/Extra /Volumes/EFI/Extra"
		ditto ${3}/.Chameleon/Extra /Volumes/EFI/Extra

		echo "Executing command: umount -f Volumes/EFI"
		"$scriptDir"UnMountEFIvolumes.sh
		returnValue=$?
		if [ ${returnValue} = 0 ]; then
			rm -R -f /Volumes/EFI
		fi
	else
		# Does an /Extra folder already exist at the target location?
		# If yes, then make a backup of it

		if [ -d "${3}/Extra" ]; then
			echo "DEBUG: Executing command: Backing up existing ${3}/Extra"
			mkdir -p "${3}/ExtraBackup"
			cp -f -R "${3}/Extra" "${3}/ExtraBackup"
			rm -f -R "${3}/Extra"
		fi

		echo "Executing command: ditto ${3}/.Chameleon/Extra ${3}/Extra"
		ditto ${3}/.Chameleon/Extra ${3}/Extra
	fi

fi


echo "==============================================="
echo "Clean Up"
echo "********"

# remove the temporary /.Chameleon directory
echo "Executing command: rm -r ${3}/.Chameleon/"
rm -r "${3}"/.Chameleon/

# remove the temporary boot sector files if they exist
if [ -d /tmp/newbs ]; then
	echo "Executing command: rm /tmp/newbs"
	rm /tmp/newbs
fi
if [ -d /tmp/origbs ]; then
	echo "Executing command: rm /tmp/origbs"
	rm /tmp/origbs
fi


exit 0
