#!/usr/bin/perl

########################################################
# No point in running if there's no logged in user,
# or if it's a command-line invocation of installer
my $user = $ENV{USER};
exit 0 unless ($user);
exit 0 if ($ENV{COMMAND_LINE_INSTALL});

# We're running as root, so we do su $user -c $DISPLAYALERT
# to run with the localization preferences of the user that
# invoked the installation in the first place.

# Also, you can check for several apps by separating app 
# names with |, ie. "Keynote|Pages|Numbers"

########################################################
# Default settings
my $RUNNING_ERROR	= "Running";
my $OTHER_RUNNING_ERROR = "";

########################################################
# STUFF WE GET FROM THE COMMAND LINE
my $PACKAGEDIR		= $ARGV[0];
my $APPLICATIONS	= $ARGV[1];

# Try to fill in errors from command line args
if (($#ARGV + 1) >= 3)
{
	$RUNNING_ERROR	= $ARGV[2];
}
if (($#ARGV + 1) >= 4)
{
	$OTHER_RUNNING_ERROR = $ARGV[3];
}

########################################################
# Find the Alert.app
my $DISPLAYALERT	= $PACKAGEDIR . "/Contents/Resources/Alert.app";

if (!-e $DISPLAYALERT)
{
	# If it's not there, try the flat-file location.
	my $wd = `pwd`;
	chomp($wd);
	$DISPLAYALERT	= $wd . "/Tools/Alert.app";
	
	# If it's not there, either, just give up.
	exit 0 unless (-e $DISPLAYALERT);
}

$DISPLAYALERT = "\"" . $DISPLAYALERT .  "/Contents/MacOS/Alert\"";

########################################################
# If we have other_running_error defined, see if some other user is running app
if ( $OTHER_RUNNING_ERROR )
{
	my $otherIsRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep -v "^$user "`);
	while ($otherIsRunning)
	{
		$ENV{'ALERT_APP_ACTION'} = $OTHER_RUNNING_ERROR;
		system("/usr/bin/su", $user, "-c", $DISPLAYALERT);
		
		$otherIsRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep -v "^$user "`);
	}		
}

# Then see if we're running app
my $iAmRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep "^$user "`);
while ($iAmRunning) 
{
	$ENV{'ALERT_APP_ACTION'} = $RUNNING_ERROR;
	system("/usr/bin/su", $user, "-c", $DISPLAYALERT);
	
	$iAmRunning = (`ps -acwwwx -ouser,command | egrep "^[^[:space:]]+[[:space:]]+$APPLICATIONS\\\$" | grep "^$user "`);
}

exit(0);
