#!/usr/bin/perl
require 5.004;
#
# Perfreview
#
# $Id: //depot/n1/tools/bin/perfreview.pl#1 $
#


my $sitename    = $ARGV[0];
my $P4PORT      = "perforce:1666";
my $p4          = "/opt/cadroot/bin/p4 -p $P4PORT";
my $once        = 1;
my $sendmailLoc = "/usr/lib/sendmail";
my $sleepTime   = 60;
my $doOutput    = 1;
my $global_mlist="maskdesign\@matrixsemi.com, matt\@matrixsemi.com, cad\@matrixsemi.com";

# Only this site will run mail commands

my $mailing_site="matrix_ca";


unless( $sitename ne "") {
  die "Site name needed!\n";
}


# Create/check a lock to wait for this process to finish

$cmd="touch /tmp/p4review.lock";
if( -e "/tmp/p4review.lock" ) {
  print "Exiting, lock exists\n";
  exit;
} else {
  # Create the lock
  print "Creating lock\n";
  system($cmd);
}


$mlist = "";
$sync_client = "";
$rfname = "";
$dosync = 0;

select(STDOUT); $| = 1;		# make unbuffered




# if -1 is given, we'll run once
$flag = shift @ARGV;
#$once = 1 if( $flag eq '-1' );



# All site will run the syncer

open(CLIENTS, "$p4 clients|") or die;

while(<CLIENTS>) {
  chop;
  
  (@cdata)=split;
  
  $sclient=$_;
  
  #$smatch="ite:$sitename";
  
  # Sync the master clients
  if($sclient =~ /_master/) {
    $cmd="$p4 -c $cdata[1] sync";
    print "$cmd\n";
    system($cmd);
  }
  
  # Sync the CDS pseudo mainline shared  clients
  if($sclient =~ /cds library/) {
    $cmd="$p4 -c $cdata[1] sync";
    #print "$cmd\n";
    #system($cmd);
  }
}


if($sitename eq $mailing_site) {
  
  do {
    # Remember highest numbered change we see, so that we can
    # reset the 'review' counter once all mail is delivered.
    # If we crash, the worst that happens is we'll send the mail
    # again.
    local( $topChange ) = 0;
    
    #
    # REVIEW - list of changes to review.
    #
    open( REVIEW, "$p4 review -t mailcounter|" ) or next;
    while( <REVIEW> ) {
      #
      # Format: "Change x user <email> (Full Name)"
      #
      local($change,$user,$email,$fullName) = /Change (\d*) (\S*) <(\S*)> (\(.*\))/;
      
      print "review $change...\n" if ($doOutput);
      open(REVIEWERS, "$p4 reviews -c $change|") or next;
      while( <REVIEWERS> ) {
	local($user2,$email2,$fullName2) = /(\S*) <(\S*)> (\(.*\))/;
	push(@reviewers, ", ") if @reviewers;
	push(@reviewers, "$email2");
      }
      close( REVIEWERS );
      
      # mark it as reviewed if there are no reviewers
      # so that script doesn't have to play catchup
      if(!@reviewers) {
	print "No reviewers...marking as reviewed\n";
	system("$p4 review -c $change -t mailcounter" );
	next;
      }
      
      print "reading change description for $change\n";
      $mdata = "";
      $line = 0;
      $gotmail = 0;
      $gotglobalmail=0;
      $nomail = 0;
      $xtramail = 0;
      $projdefined = 0;
      # We need to get the summary
      # choose first 60 chars of checkin message
      open(DESCRIBE, "$p4 describe -s $change |");
      
      while( <DESCRIBE> ) {
	chop;
	$line++;
	
	if( $line == 1 ) {
	if(/\@locked:/) {
        $gotglobalmail=1;
        }

		
	  ($rchange,$ruser,$rclient) = /Change (\d*) by (\S*)@(.*)/;
	  (@rcinfo) = split(' ',$rclient);
	  $rclient = $rcinfo[0];
	  print "CH $rchange U $ruser C $rclient\n";
	}
	if ($line == 3) {
	  $changedes = substr($_,1,60);
	  $changedes =~ s/\s*\(nomail\)\s*//i;
	  printf "$changedes\n";
	}
	if ($line >= 3) {
	  if (/\(nomail\)/i) {
	    $nomail = 1;
	  }
	  if (/xtramail/i) {
	    $xtramail = $gotmail = 1;
	    ($mlist) = /\s*xtramail\s*\=\s*(\S+)/i;
	  }
	}
	if (/^Affected files/i) {
	  close(DESCRIBE);
	  $line=0;
	}
      }
      
      close(DESCRIBE);
      
      $read = 0;
      $cmd = "$p4 client -o $rclient";
      open(WC,"$cmd|");
      while(<WC>) {
	chop;
	
	if( /^Description/ ) {
	  $read = 1;
	  next;
	}
	
	if( /^Root/ ) {
	  $read=0;
	}
	
	if( $read eq 1 ) {
	  ($minfo) = /[Mm]ail=(\S+)/;
	  ($sync)  = /[Ss]ync=(\S+)/;
	  ($pinfo) = /[Pp]roj=(\S+)/;
	  
	  if($minfo && !$nomail) {
	    if ($mlist ne "") {
	      $mlist .= ",";
	    }
	    $mlist .= $minfo;
	    $gotmail = 1;
	  }
	  
	  if( $sync ) {
	    $sync_client = $sync;
	    $dosync = 1;
	  }
	  
	  if( $pinfo ) {
	    $project = $pinfo;
	    $projdefined = 1;
	  }
	}
	next;
      }
      close(WC);
      
      # do a yp lookup for the users real name
      open(FINGER, "ypmatch $ruser passwd|");
      while(<FINGER>) {
	# get the full name
	chop;
	($rfname) = /[a-z]+:.*:\d*:\d*:([\-a-zA-Z\. ]+).*/;
      }
      close(FINGER);
      
      #      if ($nomail) {
      #          system("$p4 -c $rclient change -o $change | sed \'s\/\([nN][oO][mM][aA][iI][lL]\)\/\/g\' | $p4 -c $rclient change -f -i");
      #      }
      if ($nomail || $xtramail) {
	open (IN, "$p4 -c $rclient change -o $change |");
	open (OUT, "| $p4 -c $rclient change -f -i");
	
	while (<IN>) {
	  chop;
	  
	  next if (/xtramail/i);
	  s/\s*\(nomail\)\s*//i;
	  
	  print OUT "$_\n";
	}
	close(IN);
	close(OUT);
      }
     

	#print "$gotmail $mlist $gotglobalmail\n";
 
      if(($gotmail && $mlist ne "") || $gotglobalmail eq 1) {
	open(DESCRIBE, "$p4 describe -s $change|");
	print "Running mailer\n";
	open(MAIL, "|$sendmailLoc -t");
	#open(MAIL, ">/tmp/mail.$$");
	$masterlist="";
	# Set the mailing list contents
	if($gotmail && $gotglobalmail) {
	  $masterlist=$mlist.",".$global_mlist;
	} else {
	  if($gotmail && !$gotglobalmail) {
	    $masterlist=$mlist;
	  } else {
	    if($gotglobalmail && !$gotmail) {
	      $masterlist=$global_mlist;
	    }
	  }
	}
	print "Mailing to $masterlist\n";
	
	if ($gotglobalmail) {
	  $subject = "[p4] LOCKED library change $changedes";
	} else {
	  $subject = "[p4] $changedes";
	}

	
	print MAIL "To: $masterlist, $ruser\n",
	"From: $ruser ($rfname)\n",
	"Subject:$subject\n\n";
	
	while( <DESCRIBE> ) {
	  # don't allow single .'s through
	  $_ = "..\n" if( $_ eq ".\n" );
	  print MAIL;
	}

	print MAIL "\n\nhttp://ghost.engr.matrixsemi.com/p4db/changeView.cgi?CH=$rchange\n";
	close(MAIL);
	close(DESCRIBE);
	$mlist="";
      }
      
      $gotmail = 0;
      $topChange = $change;
      
      if( $dosync == 1 )  {
         print("Syncing client $sync_client\n");
         $dosync = 0;
         system("$p4 -c $sync_client sync") if( $topChange );
       }
      
      
      # Update counter to reflect changes reviewed.
      #
      print "Marking as reviewed $topChange\n";
      system("$p4 review -c $topChange -t mailcounter") if( $topChange );
    }
  }


}
#delete the lock
print "Clearing lock\n";
$cmd = "rm -f /tmp/p4review.lock";
system($cmd);
exit 0;