#!/usr/bin/perl

######################################
# Get this stuff from the command line
my $sourcePackagePath	= $ARGV[0];
my $resourcePath		= $sourcePackagePath . "/Contents/Resources";
my $destPath			= $ARGV[1];
my $targetVolume		= $ARGV[2];
my $runningSystemFolder	= $ARGV[3];

my $restOfLoopsPath = "/Library/Audio/Apple Loops/Apple/Apple Loops for GarageBand";

########################################################################################
my $PlistBuddy					= $resourcePath . "/PlistBuddy";
my $ALPIndex					= $resourcePath . "/ALPIndex.app/Contents/MacOS/ALPIndex";
my $GBAS						= $targetVolume . "/Library/Application Support/GarageBand/";
my $PackageRegistry				= $GBAS . "Package Registry.plist";
my $AppleLoopsIndexFolder		= $targetVolume . "/Library/Audio/Apple Loops Index/";
my $ShowContentUpdateKey		= "'Show Content Update'";

my $JamPackLoopsDir		= $destPath . $restOfLoopsPath;
########################################################################################
########################################################################################

my $SCUKeyResult = `"$PlistBuddy" -c "Print 'GarageBand 4.0':'Show Content Update'" "$PackageRegistry" 2>/dev/null`;
unless ( $? || $SCUKeyResult =~ /Does Not Exist/) 
{
	system(	$PlistBuddy, "-c", 
	"Delete 'GarageBand 4.0':'Show Content Update'", 
	$PackageRegistry);
}	

$SCUKeyResult = `"$PlistBuddy" -c "Print 'GarageBand 5.0':'Show Content Update'" "$PackageRegistry" 2>/dev/null`;
unless ( $? || $SCUKeyResult =~ /Does Not Exist/) 
{
	system(	$PlistBuddy, "-c", 
	"Delete 'GarageBand 5.0':'Show Content Update'", 
	$PackageRegistry);
}	

# Index the new loops
system(	$ALPIndex, $JamPackLoopsDir);
		
# Clean up any files like "/Library/Audio/Apple Loops Index/Update Index xxx"
opendir(DIR, $AppleLoopsIndexFolder);
while (defined(my $updateIndexToClean = readdir(DIR)))
{
	# skip if not an Update Index file ("name starts with Update Index")
	next unless $updateIndexToClean =~ /^Update Index/;
	
	# OK, so we need to delete this file
	unlink $AppleLoopsIndexFolder . $updateIndexToClean;
}
closedir(DIR);

########################################################################################
# And always exit 0
exit 0;
