#!/usr/bin/perl

# Script to make sure the autosyncer has not got stranded locks
use Date::Manip;
&Date_Init(); 

# auto sync interval in seconds
$sync_interval=300;

# lock file 
$lock_file="/tmp/p4review.lock";
$sendmailLoc = "/usr/lib/sendmail";
$p4="/usr/local/bin/p4";

# run p4 counters

$cmd="$p4 counters";

open(CMD, "$cmd|") || die ;

while(<CMD>) {
	
	chop;

	if(/change/) {
		($ig,$ig,$head)=split;
	}
	if(/mailcounter/){
	($ig,$ig,$mail)=split;
	}
}

close(CMD);

# Get the time of the head change and the mail change
# subtract the two
# if greater than interval...kill the lock file since it must be stranded
#

$cmd="$p4 describe -s $head ";

open(CMD,"$cmd|") || die;

while(<CMD>) {
	if(/pending/) {
        # ignore pending events
        exit;
}

	
	if(/Change/) {
		(@cdata)=split;
		}
}


$head_time=$cdata[6];

$cmd="$p4 describe -s $mail | head -1";


open(CMD,"$cmd|") || die;

while(<CMD>) {
	if(/pending/) {
	 # ignore pending events
	 exit;
}
	
        if(Change) {
          (@cdata)=split;
        }
}
$mail_time=$cdata[6];



$date1=&ParseDate($mail_time);
$date2=&ParseDate($head_time);
$delta=&DateCalc($date2,$date1,\$err);

(@dspec)=split(':',$delta);
$numsecs=$dspec[3]*24 + $dsspec[4]* 60 + $dspec[5] * 60;

#print "$delta $numsecs\n";

if ($numsecs > (2* $sync_interval)) {
	#print "Problem mail activated\n";
	open(MAIL, "|$sendmailLoc -t");
	print MAIL "To: sikand,roger,clifs\n",
	"From: Cron Daemon (Cron Daemon)\n",
        "Subject: Autosync un-wedge\n\n";
	print MAIL "Trying to clear stranded lock file, /tmp/p4review.lock on plague\n\n";
	print MAIL "Head change: $head at $head_time, last autosync event $mail at $mail_time\n";
	
	if( -e "/tmp/p4review.lock") {
	system("rm /tmp/p4review.lock");
		} else {
	print MAIL "\n\nCritical error: lock file does not exist, something else is wrong !!!!!\n";
	print MAIL "Diagnostic: This jobs runs as user sikand on plague\n";
	}
	close(MAIL);
	}