#!/usr/bin/perl

my $RECEIPT_NAME	= $ENV{'RECEIPT_PATH'};

#print "Going in, we're handed: $RECEIPT_NAME\n";

######################################################
#Canonicalize the path to the receipt:

# First get rid of the /Contents/Resources thing
$RECEIPT_NAME		=~ m!^(.*)/Contents/Resources(/|)!;
my $TRIMMED_RCPT	= $1;

# Fix it if no /Contents/Resources was there
if (!$TRIMMED_RCPT) {
	$TRIMMED_RCPT = $RECEIPT_NAME;
}

# now get rid of any trailing right /
$TRIMMED_RCPT		=~ m!(.*)/$!;

if ($1) {
	$TRIMMED_RCPT = $1;
}

#####################################################
# Now parse out the package name, and make a new package name
# The package name part is between the / and the .pkg
$TRIMMED_RCPT		=~ m!^(.*)/(.*)\.pkg!;
my $PACKAGE_NAME	= $2;
my $PACKAGE_PATH	= $1 . "/";

# If we come up empty, it's because there's nothing to the left of the receipt name
if (!$2) {
	$TRIMMED_RCPT		=~ m!^(.*)\.pkg!;
	$PACKAGE_NAME		= $1;
	$PACKAGE_PATH		= "";
}

# So, now we know what the old package and the new package should be
my $OLD_PACKAGE			= $PACKAGE_PATH . $PACKAGE_NAME . ".pkg";
my $NEW_PACKAGE			= $PACKAGE_PATH . "SU" . $PACKAGE_NAME . ".pkg";

#print "My Old package: $OLD_PACKAGE\n";
#print "My New package: $NEW_PACKAGE\n";

#####################################################
# What if something with the new name exists?
if (-e $NEW_PACKAGE) {
	# Make a temp folder
	my $NEW_TEMP_DUMP = `/usr/bin/mktemp -d /tmp/com.apple.pkg.RDC220.XXXX`;
	chomp $NEW_TEMP_DUMP;
	# And move the impostor there!
	system("/bin/mv", "-f", $NEW_PACKAGE, $NEW_TEMP_DUMP);
}

#####################################################
# So now we can rename the package to the new name
system("/bin/mv", "-f", $OLD_PACKAGE, $NEW_PACKAGE);

#####################################################################
# Now let's fix the Info.plist of the new package to be more wonderful
# It's conveniently located at:
my $INFO_PLIST_TO_MUNGE = $NEW_PACKAGE . "/Contents/Info.plist";

# Here's what the CFBundleID should be
my $NEW_CFBUNDLEID	= "com.apple.pkg.SU" . $PACKAGE_NAME;

# And here's PlistBuddy
my $PLISTBUDDY = $ARGV[0] . "/Contents/Resources/PlistBuddy";

# Now go stomping. Note that ALL valid packages must have this key
# So I am not going to bother to do a careful set/add thing on it
# Nor am I even going to check the return code. 
system( $PLISTBUDDY, "-c", 
		"set CFBundleIdentifier '" . $NEW_CFBUNDLEID . "'",
		$INFO_PLIST_TO_MUNGE);

# And always
exit 0;


