#!/usr/bin/env perl

`/home/heather/cronjobscripts/regcheck`;

@checkexp = `ssh ippc19 checkexp2`;

@regcheck = `ssh ippc19 'perl checkreg.pl'`;
$nebcheck = `ssh ipp117 'ps auxw | grep nebdiskd | grep -v grep | wc -l'`;

@mysqlcheck = `ssh ippc19 "mysql -h scidbm -u ipp -pipp gpc1 -e 'select count(*) from addRun \G'"`;
  $lastcopied = '';
 $lastregistered = '';
  $firstexp = '';
 $lastexp = '';
 $wrong = 0;
$stuck = 0;
 $fault = 0;
 $incomplete_dl = 0;
 $notreg = 0;
$gpc1 = 0;

foreach $line (@mysqlcheck) {
    chomp $line;
    if ($line =~ /count/) {
	$gpc1 = 1;
    }
}

foreach $line (@checkexp) {
    chomp $line;
    @split =  (/\s+/, $line);
    if ($line =~ /incomplete down/) {
	print "incomplete downloads\n";
	$incomplete_dl = $split[0];
    }
    if ($line =~ /exposures copied/) {
	print "exposures copied\n";
	$notreg = $split[0];
	
    }
     if ($line =~ /last copied:/) {
	 $lastcopied = $split[2];
    }
      if ($line =~ /first exposure:/) {
	 $firstexp = $split[2];
    }
       if ($line =~ /last exposure:/) {
	 $lastexp = $split[2];
    }
        if ($line =~ /fault/) {
	    $fault = 1;
	    $faultline = $line;
    }
} 
foreach $line (@regcheck) {
    chomp $line;
    @split =  (/\s+/, $line);
    
    if ($line =~ /last registered:/) {
	$lastreg = $split[2];
	
    }
    if ($line =~ /stuck/) {
	    $stuck = 1;
	    $stuckline = $line;
    }
     if ($line =~ /wrong/) {
	 #$datehr = `date +%H`;
	 #chomp $date;
	 #if ($date > 19 && 
	 $wrong = 0;
	 $wrongline = $line;
    }
} 


$sendtxt = 0;
$txt = '';

if ($incomplete_dl > 30) {
    $sendtxt=1;
    $txt = "$incomplete_dl incomplete download, needs to be \< 30";
}

if ($notreg > 20) {
    $sendtxt=1;
    $txt = "$notreg not registered, needs to be \< 20";
}

if ($fault) {
    $sendtxt=1;
    $txt = $faultline;
}

if ($wrong) {
    $sendtxt=1;
    $txt = $wrongline;
}

if ($stuck) {
    $sendtxt=1;
    $txt = $stuckline;
}

#print "nebcheck is $nebcheck\n";
if ($nebcheck != 1) {
    $sendtxt =1;
    $txt= "check nebdiskd on ipp117\n";
} 

if ($gpc1 == 0) {
    $sendtxt=1;
    $txt = "can't connect to gpc1";
}



# need logic for if lastcopied = previous lastcopied & != lastexp

# need logic for if lastregistered = previous lastregistered & != lastexp

if ($sendtxt > 0) {
    print "sending txt\n";
    #`mail -s "$txt" flewelling.heather@gmail.com </tmp/summit.temp`;
    #`echo "$txt" | mail -s "check ipp" 8082349303\@mailmymobile.net`;
    `echo "$txt" | mail -s "check ipp" flewelling.heather\@gmail.com`;
    `echo "$txt" | mail -s "check ipp" ps-ipp-ops\@ifa.hawaii.edu`;
    `echo "$txt" | mail -s "check ipp" mopsadmin\@ifa.hawaii.edu`;


} else {
    print "no need to send txt\n";
   # `echo "no need to send txt" | mail -s "ipp ok" flewelling.heather\@gmail.com`;
}
