#!/usr/bin/perl
my $target = $ARGV[2];
my $pkg = $ARGV[0];

###################################################################################
my $ALERT = "$ARGV[0]/Contents/Resources/Alert.app/Contents/MacOS/Alert";
my $SENDER = "$ARGV[0]/Contents/Resources/SlimSender";
my $APP = "MainStage";
my $APP_IS_RUNNING = 0;
my $APP_RUNNING_CURRENT_USER = 0;
my $APP_RUNNING_OTHER_USER = 0;
###################################################################################

my @switchedPIDs = ();
my @activePIDs = ();

# First remove the extraneous nib support files
deleteFiles( "$pkg/Contents/Resources/RemoveFilesList" );

# abort if alert is unavailable
if (! -e $ALERT) {
	exit(1);
}

# retrieve MainStage PIDs, if any
my $PROC = `/usr/bin/killall -dc "$APP" 2> /dev/null`;
if (($? >> 8) != 0) {
	exit(0);
}

# get current user ID
my $currentUID = `/usr/bin/id -u "$ENV{USER}"`;
if (($? >> 8) != 0) {
	$currentUID = -1;
}
chomp $currentUID;

# try to close any switched MainStage PIDs
my @PROCS = split(/\n/, $PROC);
foreach (@PROCS) {
	if (! -e $SENDER) {
		last;
	}
	if ($_ =~ m/sig:.+cmd:$APP.+pid:([0-9]+).+dev:.+uid:([0-9]+)/) {
		my $pid = $1;
		my $processUID = $2;
		if ($processUID != $currentUID) {
			print "Attempting to close MainStage PID $pid\n";
			#`"$SENDER" -p $pid -e aevtquit`;
			system("$SENDER", "-p", "$pid", "-e", "aevtquit");
			sleep(3);	
		}
	}
	else {
		next;
	}
}

# retrieve MainStage PIDs (again), if any
$PROC = `/usr/bin/killall -dc "$APP" 2> /dev/null`;
if (($? >> 8) != 0) {
	exit(0);
}
$APP_IS_RUNNING = 1;

while ($APP_IS_RUNNING == 1) {

	# classify MainStage PIDs as running under active user or switched user
	@switchedPIDs = ();
	@activePIDs = ();
	my @PROCS = split(/\n/, $PROC);
	foreach (@PROCS) {
		if ($_ =~ m/sig:.+cmd:$APP.+pid:([0-9]+).+dev:.+uid:([0-9]+)/) {
			my $pid = $1;
			my $processUID = $2;
			if ($processUID == $currentUID) {
				push(@activePIDs, $pid);
				$APP_RUNNING_CURRENT_USER = 1;
			}
			else {
				push(@switchedPIDs, $pid);
				$APP_RUNNING_OTHER_USER = 1;
			}
		}
		else {
			next;
		}
	}

	# current user message has priority over other user message
	if ($APP_RUNNING_CURRENT_USER) {
		$ENV{'ALERT_APP_ACTION'} = "AppRunning";
	}
	elsif ($APP_RUNNING_OTHER_USER) {
		$ENV{'ALERT_APP_ACTION'} = "AppRunningOtherUser";
	}
	else {
		$ENV{'ALERT_APP_ACTION'} = "AppRunning";
	}

	#`/usr/bin/su $ENV{USER} -c "$ALERT"`;
	system ("/usr/bin/su", $ENV{USER}, "-c", "\"$ALERT\"");
	
	# terminate if there is no SWU or Installer process for the active user
	`/usr/bin/killall -u $ENV{USER} -s "Software Update" 2> /dev/null`;
	if (($? >> 8) != 0) {
		`/usr/bin/killall -u $ENV{USER} -s "Installer" 2> /dev/null`;
		if (($? >> 8) != 0) {
			exit(0);
		}
	}
	
	# reset for next loop iteration
	$APP_RUNNING_CURRENT_USER = 0;
	$APP_RUNNING_OTHER_USER = 0;
	
	$PROC = `/usr/bin/killall -dc "MainStage" 2> /dev/null`;
	$APP_IS_RUNNING = !($? >> 8);

}

exit(0);

sub deleteEmptyDir
{
	opendir(DIR, $_[0] );
	my @files = grep( !/^\./, readdir(DIR)); 
	closedir(DIR);
	my $count = @files;
	if( $count == 0 ){ `/bin/rm -Rf "$_[0]"` }
}

sub deleteFiles
{
	open (FILE, $_[0]) || die ;

	while (defined ($deleteme = <FILE>)) {
		chomp $deleteme;
		if (length($deleteme) > 0)
		{
			print("cleaning up: $target/$deleteme\n");
			deleteTree($target . $deleteme);
		}
	}
}

sub deleteEmptyDirs
{
	open (FILE, $_[0]) || die ;

	while (defined ($deleteme = <FILE>)) {
		chomp $deleteme;
		if (length($deleteme) > 0)
		{
			print("cleaning up: $target/$deleteme\n");
			deleteEmptyDir($target . $deleteme);
		}
	}
}

sub deleteTree
{
    my $path            = $_[0];

    if (-e $path)
    {
        if (-d $path
            && !(-l $path))
        {
            local* THEDIR;
            my $file;

            opendir THEDIR, $path;

            while ($file = readdir THEDIR)
            {
                if ($file ne '.' && $file ne '..')
                {
                    deleteTree($path . "/" . $file);
                }
            }

            closedir THEDIR;

            rmdir $path;
        } else {

            unlink $path;
        }
    } else {
        if (-l $path)
        {
            unlink $path;
        }
    }
}