#! /usr/bin/perl

require 5.002;
use strict;
use Getopt::Std;
use Data::Dumper;
use FileHandle;
use File::Basename;
#use LWP::Simple; 
use LWP::UserAgent; 

###MAIN####
our ($opt_h, $opt_S);
getopts("hS:");
if ($opt_h) {
    print
"Usage: $0 [-h] [-S save-dir]
	-h	Print this message
	-S save_dir	- Save stats.html files in save_dir INSTEAD of
			  generating report file.\n";
    exit(0);
}

#my $serial_file = "/home/dc11/dcmgr/web_retrieve/serial";
# default
#my $serial_file = "/home/dcmgr/qc_utils/serial";
my $serial_file = "/work/dc6/ftp/outgoing/taira/WQC/serial";

my $data = &initDataBase($serial_file);
my $query = {'Network' => 'BK', 'Baler_type' => 'baler44'};
my $stationList = &getBalers($data, $query);
my $stats = &parseBaler44Stats($stationList);
&printResults($stats) unless ($opt_S);
exit 0;

###SUBROUTINE LIBRARY###
sub printResults($){
    my $time = `date`;
    my $header = "-------------------------------------------------------------------------\n";
    $header   .= "    BALER 44 SUMMARY REPORT as of $time";
    $header   .= "-------------------------------------------------------------------------\n";
    my $stats = $_[0];
    my $OUTPUT_FORMAT = '%9s %-8s %-21s %-12s %-10s %-12s %-11s %-6s %-20s';
    print "$header";
    printf "$OUTPUT_FORMAT", "Station","Status","LastWrite", "InUse","InUseFree", "Reserve", "Reservefree", "Circ", "Alerts";
    print "\n";
    foreach (sort {$a->{'name'} cmp $b->{'name'}} @$stats){
	printf "$OUTPUT_FORMAT", $_->{'name'}, $_->{'status'}, $_->{'lastWrite'},  
		$_->{'INUSECap'}, $_->{'INUSEPctFree'}, 
		$_->{'RESERVECap'},  $_->{'RESERVEPctFree'}, 
		$_->{'circ'}, $_->{'Alerts'};
	print "\n";
    }
    return 0;
}


#read stats files for subset of stations, currently only BK
sub parseBaler44Stats($){
   my $listRef = $_[0];
   my @stats = ();
   my $ua = LWP::UserAgent->new("timeout" => 60);
   my $prot = 'http://';
   my $remotePath = '/stats.html';

   foreach my $host (@$listRef) {
      my ($name, $status, $lastWrite, $INUSEPctFree, $INUSECap, $RESERVEPctFree, $RESERVECap, $circ);
      my $res = $ua->get($prot . $host->{'B_hostname_for_data'} . ':' . $host->{'B_port_web'} . $remotePath);
      if ($res->is_success) {
	  my @lines = split(/\n/, $res->as_string());
	  if ($opt_S) {
	      my $statsfile = "$opt_S/$host->{'S.N.'}.html";
	      open outFH, ">$statsfile" or die "Can't open $statsfile: $!\n";
	      print outFH join "\n", @lines;
	      print outFH "\n";
	      close outFH;
	      next;
	  }

	  foreach (@lines) {
	      $status     = $1 if $_ =~ /MEDIA\s(\w+)$/;
	      $lastWrite  = $1 if $_ =~ /media last write time: (\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d)/;
	      ($INUSECap, $INUSEPctFree) = ($2, $3)
		  if ($_ =~ /^MEDIA site \d crc=\w+\s+IN USE\s+state:\s+(ACTIVE|READY)\s+capacity=(.*\w\w)\s+free=(.*%)$/);
	      ($RESERVECap, $RESERVEPctFree) = ($1, $2)
		  if ($_ =~ /^MEDIA site \d crc=\w+\s+RESERVE\s+state:\s+READONLY\s+capacity=(.*\w\w)\s+free=(.*%)$/);
	      $circ = 'yes' if $_ =~ /circ=sdata/;
	  }
	  $circ = 'no' if $circ eq undef and $status ne undef;
	  push(@stats, {'name' => $host->{'S.N.'}, 'status' => $status, 
		   'lastWrite' => $lastWrite, 'INUSECap' => $INUSECap, 
		   'INUSEPctFree' => $INUSEPctFree, 'RESERVECap' => $RESERVECap, 
		   'RESERVEPctFree' => $RESERVEPctFree, 'circ' => $circ});
      }
      else {
	  push(@stats, {'name' => $host->{'S.N.'}, 'Alerts' => "Unable to connect to remote host"});
      }
  }
  return \@stats;
}

#returns subset of balers based on query
sub getBalers($$){
    my @list = ();
    my ($dataRef, $params) =  @_;
    foreach my $balerHashRef (@$dataRef){
	my $match = 1;
	foreach my $key (keys %{$params}){
	    $match = 0 if ($balerHashRef->{$key} ne $params->{$key});
	}
    push (@list, $balerHashRef) if $match;
    }
    return \@list;
}

sub initDataBase($){
  my $serialFile = $_[0];     #get arguments

  #values used to parse file
  my $line_regex = '^\w{3,4}\.\w{2}\s';
  my @keys =  ("S.N.", "serial_number", "pw", 
	       "Q330_hostname", "Q_web_port", 
	       "Q_base_port", "Baler_type",  
	       "B_hostname_for_data", 
	       "B_port_web", "B_port_base", 
	       "B_port_on", "Name", "Network");

  #initialize array of hash references
  my @data;

  #open file
  open(my $fh, $serial_file) or die "cannot open < $serial_file: $!";

  #read file conents into hash
  while (<$fh>) {
      next unless $_ =~ m/$line_regex/;
      chomp;
      my @values = split(/\s+/,$_);
      my $tmp;
      push(@values, split(/\./,$values[0]));
      for (my $i = 0; $i < scalar(@values); $i++){
	  $tmp->{$keys[$i]} = $values[$i];
      }
      push(@data, $tmp);
  }
  close($fh);
  return \@data;
}
