#!/usr/bin/env perl

# Find the percentage of migration test jobs that succeed over a given time period
# $Id: migration_stats.pl,v 1.1 2008-04-23 16:22:14 bgietzel Exp $ 

use Getopt::Long;
use Cwd;
use Time::Local;

use lib $ENV{'NMI_LIB'} || "/opt/nmi/lib";
use NmiConf;
use NmiTools;
use NmiStats;

GetOptions('mailto=s'  => \$main::opt_mailto,
           'days=s'    => \$main::opt_days,
           'help'      => \$main::opt_help,
           'nmiconf=s' => \$main::opt_nmiconf);

## ---------------------------------------------
## Load NMI Configuration
## ---------------------------------------------
my %conf = NmiConf::init($main::opt_nmiconf);
use NmiDatabaseVariables;
require NmiDatabase;

my $days = 1;
my %results;
my @objs = ();


if (defined $main::opt_help) {
  print <<"END";
usage: $0 [--mailto=<addrList>] [--days=<days to include, defaults to 1>] [--help]
END
  exit 0;
}    

if (defined($opt_days)) {
  $days = $opt_days;
} 

if (defined($opt_mailto)) {
  $mailto = $opt_mailto;
} else {
  die "You must specify an address for mailto\n";
}

## Run @ CERN, time = GMT
# my $threshold_date = datetime_offset(0, 0, -7, -$days);
my $threshold_date = datetime_offset(0, 0, 0, -$days);

  # Fetch migration test results from the database.
  my $cmd = qq/SELECT runid, result from $NmiDatabaseVariables::DB_TABLE_RUN WHERE start > '$threshold_date' and description="JOB MIGRATION TEST" and user='eticsbld'/;
  my $handle = NmiDatabase::execute( $cmd );
  while ( my $row = $handle->fetchrow_hashref() ) {
      my $runid = $row->{'runid'};
      my $result = $row->{'result'};
      $results{$runid} = $result;
  }

  my $total = 0, $success = 0, $removed = 0, $inprogress = 0, $percent = 0;
  foreach my $runid (keys %results) {

      my $result = $results{"$runid"}; 
      $total++;
      print "RESULT: $result\n";
      if ( $result < 0 ) {
        $removed++;
      } elsif (defined($result)) {
        if ($result == 0) {
          $success++;
          print "SUCCESS: $success\n";
        } else {
          $inprogress++;
          print "IN PROGRESS: $inprogress\n";
        }
      }
  }
  $percent = int( ($success * 100) / $total);  
  print "PERCENT is $percent\n";

  $handle->finish();

  &send_simple_report();


## ---------------------------------------------
## Send an email report
## ---------------------------------------------

sub send_simple_report {

  my $subject = "ETICS -> UW JOB MIGRATION REPORT\n";
  my $body = "my_results";
  my $hostname = `hostname`;
  chomp($hostname); 
  my $condor_version = `/opt/condor/bin/condor_version`;
  chomp($condor_version);
  my $jobrouter_version = `/opt/condor/sbin/condor_schedd.V7 -version`;
  chomp($jobrouter_version);
  my $metronome_version = `/opt/nmi/bin/nmi_version`;
  chomp($metronome_version);	
 
  open(LOG, ">", $body) || die "error creating $body: $!\n";

      print LOG "JOBS SUBMITTED FROM $hostname TO nmi-etics.cs.wisc.edu ";
      print LOG "OVER THE PAST $days days\n";
      print LOG "=======================================================================\n";
      print LOG "Total migration jobs submitted: $total\n";
      print LOG "Number succeeded: $success\n";
      print LOG "Number removed $removed\n";
      print LOG "Number in progress $inprogress\n";
      print LOG "% success (all jobs): $percent\n";
      print LOG "% success (completed jobs): $percent\n\n";

      print LOG "CONDOR_VERSION: \n$condor_version\n\n";
      print LOG "JOBROUTER_VERSION: \n$jobrouter_version\n\n";
      print LOG "METRONOME_VERSION: \n$metronome_version\n";

      # recalculate the success, only counting completed jobs
      $total = $total - $inprogress;
      $percent = int( ($success * 100) / $total);  

  close LOG;

  if( $mailto ne "" ) {
    foreach my $email ( split /,/, $mailto) {
      if ($email ne "") {
        system("mail -v -s \"$subject\" $email <$body");
      }
    }
  }
}


## ---------------------------------------------
## Offset the datetime from GMT 
## ---------------------------------------------

sub datetime_offset {
    my ($off_sec, $off_min, $off_hour, $off_day) = @_;
    my $now = time  . "\n";
    my $interval = ($off_sec) +
                   ($off_min * 60) +
                   ($off_hour * 60 * 60) +
                   ($off_day * 60 * 60 * 24);
    my $past = $now + $interval;

    my ($sec, $min, $hour, $day, $mon, $year) = gmtime($past);
    $year += 1900;
    $mon += 1;
    $mon = "0" . $mon if $mon < 10;
    $sec = "0" . $sec if $sec < 10;
    $min = "0" . $min if $min < 10;
    $hour = "0" . $hour if $hour < 10;

    return "$year-$mon-$day $hour:$min:$sec";
}
