#!/usr/bin/perl

my $TARGET = $ARGV[2];
my $SYSTEM_VERS = "$TARGET/System/Library/CoreServices/SystemVersion.plist";

if (CheckVersion( $SYSTEM_VERS, "10.6", "ProductVersion", "<" )) {

	system("/bin/mv", "$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper-a.plist",
		"$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper.plist");
	system("/bin/rm", "$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper-b.plist");
	
} else {

	system("/bin/mv", "$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper-b.plist",
		"$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper.plist");
	system("/bin/rm", "$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper-a.plist");
	
}

if (CheckVersion($SYSTEM_VERS, "10.5", "ProductVersion", "<")) {
	# we are pre-leopard, remove launchd
	system("/bin/rm", "-f", $ARGV[2] . "/System/Library/LaunchDaemons/com.apple.RFBEventHelper.plist");
	# remove the directories of they are empty
	system("/bin/rmdir", $ARGV[2] . "/System/Library/LaunchDaemons");
} else {
	system("/bin/launchctl", "load", "$TARGET/System/Library/LaunchDaemons/com.apple.RFBEventHelper.plist");
}

sub CheckVersion
{
    my $path            = $_[0];
    my $version         = $_[1];
    my $keyName         = $_[2];
    my $operator        = $_[3];
    
    my $oldSeperator;
    my $plistData;
    my @items;
    my $item;
    my $versiondata;
    my $i;
    my @theVersionArray;
    my %versiondata;
    my @versionArray;

    # if there's no THERE there, we return FALSE
    if (! -e $path) {
        return 0;
    }

    if (!$operator) {
        $operator = "==";
    }

    $oldSeperator = $/;
    $/ = \0;

    open( PLIST, "$path") || do {
        return 0;
    };

    $plistData = <PLIST>;
    $plistData =~ /<dict>(.*?)<\/dict>/gis;

    @items = split(/<key>/, $plistData);

    shift @items;
    foreach $item (@items) {
        $item =~ /(.*?)<\/key>.*?<string>(.*?)<\/string>/gis;
        $versiondata{ $1 } = $2;
    }

    close(PLIST);

    $/ = $oldSeperator;

    @theVersionArray = split(/\./, $versiondata{$keyName});
    for ($i = 0; $i < 3; $i++) {
        if(!$theVersionArray[$i]) {
            $theVersionArray[$i] = '0';
        }
    }

    @versionArray = split(/\./, $version);
    
    my $actualVersion;

    for ($i = 0; $i < 3; $i++) {
        if (($theVersionArray[$i] != $versionArray[$i]) or ($i == 2)) {

            $actualVersion = $theVersionArray[$i];
            $version = $versionArray[$i];

            last;
        }
    }

    my $expression = '$actualVersion ' . $operator . ' $version';
    if( eval ($expression) )
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
