#!/bin/bash

echo "==============================================="
echo "Main EFI System Partition Post-Install Script"
echo "*********************************************"
echo "-----------------------------------------------"
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


# Before starting - we'd better check to see if the user selected
# both the standard and the EFI system partition install options.
# If they did then the standard install will have already be run.
# Therefore, we will not run this.

if ! [ -f "${3}"/.Chameleon/nullstandard ]; then
	# OK to continue

	#echo "==============================================="
	#echo "Apple Installer Package Variables"
	#echo "*********************************"
	#echo "DEBUG: $ 1 = Full path to the installation package the installer app is processing: " $1
	#echo "DEBUG: $ 2 = Full path to the installation destination: " $2
	#echo "DEBUG: $ 3 = Installation volume (mountpoint) to receive the payload: " $3
	#echo "DEBUG: $ 4 = Root directory for the system: " $4
	#echo "DEBUG: Script Name: " $SCRIPT_NAME
	#echo "DEBUG: Package Path: " $PACKAGE_PATH
	#echo "DEBUG: Installer Temp: " $INSTALLER_TEMP
	#echo "DEBUG: Full path to the temp directory containing the operation executable: " $RECEIPT_PATH
	#echo "-----------------------------------------------"
	#echo ""


	# Initialise Script Globals

	stage0Loader="boot0"
	stage0LoaderDualBoot="boot0hfs"
	stage1LoaderHFS="boot1h"
	stage1LoaderFAT="boot1f32"
	stage2Loader="boot"

	targetVolumeTemp=$3
	targetDeviceTemp=$( df "${targetVolumeTemp}" | sed -n '2p' | awk '{print $1}' )

	targetVolume="/Volumes/EFI"
	targetDevice=${targetDeviceTemp%s*}s1
	targetDeviceRaw=${targetDevice/disk/rdisk}
	targetDisk=${targetDevice%s*}
	targetDiskRaw=${targetDisk/disk/rdisk}
	targetSlice=${targetDevice#*disk*s}



	echo "==============================================="
	echo "DEBUG: display script variables"
	echo "***************************"

	echo "DEBUG: stage0Loader: Disk loader is ${stage0Loader}"
	echo "DEBUG: stage0LoaderDualBoot: Disk loader is ${stage0LoaderDualBoot}"
	echo "DEBUG: stage1LoaderHFS: Partition loader is ${stage1LoaderHFS}"
	echo "DEBUG: stage1LoaderFat: Partition loader is ${stage1LoaderFAT}"
	echo "DEBUG: stage2Loader: Filesystem loader is ${stage2Loader}"
	echo "DEBUG: targetVolumeTemp: Volume is ${targetVolumeTemp}"
	echo "DEBUG: targetDeviceTemp: Volume device is ${targetDeviceTemp}"
	echo "DEBUG: targetVolume: Volume is ${targetVolume}"
	echo "DEBUG: targetDevice: Volume device is ${targetDevice}"
	echo "DEBUG: targetDeviceRaw: Volume raw device is ${targetDeviceRaw}"
	echo "DEBUG: targetDisk: Disk device is ${targetDisk}"
	echo "DEBUG: targetDiskRaw: Disk raw device is ${targetDiskRaw}"
	echo "DEBUG: targetSlice: Volume slice is ${targetSlice}"
	echo "-----------------------------------------------"
	echo ""


	# Check to see if the selected disk uses a GPT

	bootuuid=$( diskutil info "$targetDeviceTemp" | grep Volume\ UUID | awk {'print $3'} )
	partitiontable=$( diskutil list ${targetDeviceTemp%s*} | sed -n '3p' | awk '{print $2}' )

	if [ ${partitiontable} = "GUID_partition_scheme" ]; then
		echo "Confirm this is a GPT partitioned disk."

		# Double check we can see the selected partition and it's of the right type

		"$scriptDir"CheckProceed.sh "${targetVolumeTemp}" "${targetDeviceTemp}"
		returnValue=$?
		if [ ${returnValue} = 0 ]; then
			# OK to proceed


			# Does a GRUB or Linux loader already exist in the disk's MBR?
			# The script returns 1 if yes, 0 if no.

			"$scriptDir"CheckGRUBLinuxLoader.sh "${targetDisk}"
			returnValue=$?
			if [ ${returnValue} = 0 ]; then
				# OK to proceed


				# check for a 4-byte Windows disk signature in the disk's MBR.
				# the following script returns 1 if a Windows disk signature exists, and 0 if not.

				"$scriptDir"CheckWindowsDiskSignature.sh "${targetDisk}"
				diskSigCheck=$?


				# check for existing bootloaders in the disk's MBR
				# and find out if we can write the Chameleon boot files.
				# the following script returns 0 if we can proceed
				# with writing the boot files, and 1 for not.

				"$scriptDir"CheckDiskMicrocode.sh "${targetDisk}" "${diskSigCheck}" 
				diskupdate=$?


				# check the format of the selected partition.
				# the following script returns 1 if HFS
				# the following script returns 2 if MSDOS
				# the following script returns 0 if nothing

				"$scriptDir"CheckFormat.sh "${targetDevice}"
				espformat=$?


				# Determine the partition scheme of the selected disk
				# is it GPT or a hybrid GPT/MBR

				"$scriptDir"CheckPartitionScheme.sh "${targetDisk}"


				# Unmount ALL mounted volumes named EFI
				# the following script returns 0 if it succeeds
				# the following script returns 1 if it fails to un-mount any EFI volume

				"$scriptDir"UnMountEFIvolumes.sh
				returnValue=$?
				if [ ${returnValue} = 0 ]; then
					# OK to proceed


					# If diskupdate is flagged as 0 then the stage 0 loader can be written to the MBR
					if [ ${diskupdate} = 0 ]; then
						"$scriptDir"WriteChameleonStage0.sh "${diskupdate}" "${diskSigCheck}" "${stage0Loader}" "${stage0LoaderDualBoot}" "${targetDisk}" "${targetVolumeTemp}"
					fi

					# Write the stage 1 loader to the partition boot sector
					"$scriptDir"WriteChameleonStage1.sh "${espformat}" "${stage1LoaderHFS}" "${stage1LoaderFAT}" "${targetVolumeTemp}" "${targetDeviceRaw}" "${targetVolume}"

					# Write the stage 2 loader to the root of the selected partition
					"$scriptDir"WriteChameleonStage2.sh "${espformat}" "${stage2Loader}" "${targetVolumeTemp}" "${targetDevice}" "${targetVolume}"

					# Set the active partition ONLY if Windows is not installed
					"$scriptDir"SetActivePartition.sh "${espformat}" "${diskSigCheck}" "${targetDiskRaw}" "${targetSlice}" "${targetVolumeTemp}"
			
				fi
			else
				# Write error to Chameleon_Error_Log file
				"$scriptDir"WriteInstallerLog.sh "${targetVolumeTemp}" "Error: Target drive has existing GRUB / Linux loader in the MBR - Not sure how to continue"
			fi
		fi
	else
		echo "ERROR Volume is not on a GPT partitioned disc."
		# Write error to Chameleon_Error_Log file
		"$scriptDir"WriteInstallerLog.sh "${targetVolumeTemp}" "Error: ${targetVolumeTemp} is not on a GPT partitioned disc."
	fi
else
	echo "Note: User selected both locations for installation - So not Continuing with EFI System Partition script"
	# Write error to Chameleon_Error_Log file
	"$scriptDir"WriteInstallerLog.sh "${3}" "Note: User selected both locations for installation. Not continuing with the script for installing to the EFI system partition"
fi

exit 0
