#!/usr/bin/env perl

# get the program name
@COMPONENTS = split(/\//,$0);
$myname = $COMPONENTS[$#COMPONENTS];
print "$myname:starts.................\n";

#
# look for instances of prog being run by this user
#
$prog = $ARGV[0];
if ($prog eq "") {
	$prog = "webclient";
}
$hardstop = 0;
if ($ARGV[1] ne "") {
	$hardstop = 1;
}
print "cleaning up for program: $prog.\n";
$logname = $ENV{"LOGNAME"};

if (($prog ne "webclient") && ($prog ne "webbot") || $hardstop) {
	goto really_kill;
}

open(PS,"ps -u$logname |");
$found = 0;
while(<PS>) {
	if(index($_,$prog)>0) {
		# found one -- get the process id
		@split = split(/ +/,$_);
		$pid = $split[2];
		# send it a SIGTERM
		print "kill -TERM $pid\n";
		system("kill -TERM $pid");
		$found++;
	}
}
print "$myname: found $found copies of $prog running.\n";
close PS;

if ($found == 0) {goto exit_now;}

sleep(60);

really_kill:
open(PS,"ps -u$logname |");
$found = 0;
while(<PS>) {
	if(index($_,$prog)>0) {
		# found one -- get the process id
		@split = split(/ +/,$_);
		$pid = $split[2];
		# make sure it goes away this time
		print "kill -9 $pid\n";
		system("kill -9 $pid");
		$found++;
	}
}
print "$myname: found $found copies of $prog still running.\n";

exit_now:
print "$myname:exits..................\n";
