#!/usr/bin/perl
use POSIX;

($process, $year,$mon,$day,$hour,$min,$sec)=@ARGV;

if ($#ARGV < 6) {
        print "Usage:\n";
        print "$0 [Process][Year] [Month] [Day] [Hour] [Minute] [Second]\n";
        exit(1);
}

$system = `/bin/date +%s`;

@months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
@procs= grep { $_ =~ /$process/i and $_ !~ /$0/ } `/bin/ps -eo lstart,pid,user,comm --sort lstart --no-headers`;
chomp(@procs);

$wday = ?;
$yday = ?;
$proc = 0;
for ($i=0; $i < $#procs; $i++){
	($wd_namep ,$m_namep, $dayp, $timep, $yearp, $pidp, $user, $comm) = split(" ",$procs[$i]);
	($hourp, $minp, $secp) = split (":",$timep);
	
	$monp = 0;
	for ($j=0; $j <= $#months; $j++){
		if ($months[$j] =~ $m_namep){
			$monp = $j;
			$j = 13;
		}
	}
	$yearp = $yearp - 2000;
	$yearp = 100 + $yearp;

	$start_proc = mktime($secp,$minp,$hourp,$dayp,$monp,$yearp,$wday,$yday,-1);
#	print "\n\n$procs[$i]\n";
#	print "Start: $start_proc\n";
#	print ctime($start_proc);

	$limit = mktime(($secp+$sec),($minp+$min),($hourp+$hour),($dayp+$day),($monp+$mon),($yearp+$year),$wday,$yday,-1);
#	print "Limit: $limit\n";
#       print ctime($limit);

	if ($system > $limit){
		$proc++;
		$return .= " $comm($pidp),";
	}
}
$return =~ s/,$//g;

if ($year){$output .= " $year year(s)";}
if ($mon){$output .= " $mon month(s)";}
if ($day){$output .= " $day day(s)";}
if ($hour){$output .= " $hour hour(s)";}
if ($min){$output .= " $min min(s)"; }
if ($sec){$output .= " $sec sec(s)"; }

if ($proc > 0){
        printf ("Critical - %d processes running with name \'$process\' more then%s: %s|users=%d;;;;\n", $proc, $output, $return, $proc);
        exit (2);
}else {
        printf ("Ok - %d processes running with name \'$process\' more then%s: %s|users=%d;;;;\n", $proc, $output, $return, $proc);
        exit (0);
}
