#!/bin/bash

echo "==============================================="
echo "Main Standard 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



# Check to see if the user selected both the standard and the
# EFI system partition install options. If they did then let's
# remove the nullESP file the installer would have added to the
# temporary folder to stop the Stage 2 script trying to mount
# /Volumes/EFI.

if [ -f "${3}"/.Chameleon/nullESP ]; then
	echo "Note: User selected both install options - Removing temporary nullESP file to stop Stage 2 script trying to mount /Volumes/EFI"
	rm "${3}"/.Chameleon/nullESP
	echo ""
fi



#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"

targetVolume=$3
targetDevice=$( df "${targetVolume}" | sed -n '2p' | awk '{print $1}' )
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: 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 "DEBUG: targetResources: Boot Resources is ${targetResources}"
echo "-----------------------------------------------"
echo ""



# Double check we can see the selected partition and it's of the right type
# if not the following script returns to indicate failure.

"$scriptDir"CheckProceed.sh "${targetVolume}" "${targetDevice}"
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=$?


		# check the partition scheme used for the selected disk.
		# the following script returns 1 if GPT
		# the following script returns 2 if GPT/MBR
		# the following script returns 3 if MBR
		# the following script returns 0 if nothing

		"$scriptDir"CheckPartitionScheme.sh "${targetDisk}"
		partitionTable=$?
		if [ ${partitionTable} = 3 ]; then
			# If MBR partition scheme then check for FAT16 or FAT32

			# the following script returns 1 if FAT16
			# the following script returns 2 if FAT32
			# the following script returns 0 if nothing

			"$scriptDir"CheckFatType.sh "${targetDeviceRaw}"
			fatType=$?
		fi

		if [ "${fatType}" = 1 ] && [ "${partitionTable}" = 3 ]; then
			echo "ERROR: - Can't install to a device using FAT16"
			# Write error to Chameleon_Error_Log file
			"$scriptDir"WriteInstallerLog.sh "${3}" "${3} is a FAT16 device - Chameleon boot files not written"
		else
			# Continue if the selected device is not a FAT16 format device

			# 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}" "${targetVolume}"
			fi

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

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

			# Set the active partition ONLY if Windows is not installed
			"$scriptDir"SetActivePartition.sh "${espformat}" "${diskSigCheck}" "${targetDiskRaw}" "${targetSlice}" "${targetVolume}"			
		fi
	else
		# Write error to Chameleon_Error_Log file
		"$scriptDir"WriteInstallerLog.sh "${targetVolume}" "Error: Target drive has existing GRUB / Linux loader in the MBR - Not sure how to continue"
	fi
else
	# Write error to Chameleon_Error_Log file
	"$scriptDir"WriteInstallerLog.sh "${targetVolume}" "Error: ${targetVolume} couldn't be found or the disk doesn't use slices"
fi

exit 0
