#!/usr/bin/perl

use strict;

our $RESOURCES = $ARGV[0]."/Contents/Resources";
our $TARGET = $ARGV[2];
our $UPDATER = $TARGET . "/Applications/Utilities/SuperDrive Firmware Update.app";
our $HOME = $ENV{'HOME'};
our $USER = $ENV{'USER'};

#Only do this if we are installing to the boot volume
if ($TARGET eq "/")
{
	#And we're authenticated as root
	if ($< == 0)
	{
		#Go through each item in the array, and make sure $UPDATER doesn't already exist
		my $found = 0;
		my $i = 0;
		while (! $found)
		{
			my $invocation = qq{"$RESOURCES/PlistBuddy" } .
				qq{"-c" "print AutoLaunchedApplicationDictionary:$i:Path" } .
				qq{"$HOME/Library/Preferences/loginwindow.plist"};
		
			my $path = `$invocation`;
			my $errorCode = $? >> 8;

			if ($errorCode != 0)
			{
				last;
			}

			chomp $path;
			
			if ($path =~ "Does Not Exist")
			{
				last;
			}
			
			if ($path eq $UPDATER)
			{
				$found = 1;
			}
						
			$i ++;
		}
		
		if (!$found)
		{
		
			my $tempScript = `/usr/bin/mktemp /tmp/PMG5Update.XXXXXXXX`;
			chomp $tempScript;

			my $invocation = qq{"$RESOURCES/PlistBuddy" } .
				qq{"-c" "add AutoLaunchedApplicationDictionary array" } .
				qq{"-c" "add AutoLaunchedApplicationDictionary:0 dict" } .
				qq{"-c" "cd AutoLaunchedApplicationDictionary:0" } .
				qq{"-c" "add Path string '$UPDATER'" } .
				qq{"-c" "add Hide bool false" } .
				qq{"-c" "add InstallerAdded bool true" } .
				qq{"$HOME/Library/Preferences/loginwindow.plist" };
				
			open (SCRIPT, ">$tempScript");
			print SCRIPT "#!/bin/sh\n\n";
			print SCRIPT "$invocation\n\n";
			close SCRIPT;
			
			`/bin/chmod +rx $tempScript`;
			`/usr/bin/su -m "$USER" -c $tempScript`;
			unlink $tempScript;
		
		}
		
	}
}

exit 0;

