#!/usr/bin/perl

# AppleVNCServer 1.0 (ARD 2.0, 2.1) has the version.plist file in the wrong place. 
# In ARD 2.2, we have it in the right place.
# Thus, if a user installs 2.2 and then installs 2.0, they end up with a broken version of AppleVNCServer that
# still claims to be a correct version. Ugh.
# To fix this, we're going to blow away the AppleVNCServer.bundle if it looks like it's version <= 1.1, since
# this installer will put down another copy.

my $TARGET			= $ARGV[2];
my $VNC_SERVER		= $TARGET . "/System/Library/CoreServices/RemoteManagement/AppleVNCServer.bundle/";
my $VNC_VERSION		= $VNC_SERVER . "Contents/version.plist";

# If no VNC Server, we can leave.
exit 0 if (!-e $VNC_SERVER);

# If the version of VNC Server is ours or earlier, blow it away and let it get reinstalled.
if ((!-e $VNC_VERSION) or
	CheckVersion($VNC_VERSION, "1.1", "CFBundleShortVersionString", "<=")) 
{
	system("/bin/rm", "-rf", $VNC_SERVER);
}

exit(0);

########################################################

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

    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;
    }

}

