#!/opt/SUNWstade/bin/perl -I/opt/SUNWstade/lib
#<copyright>
# ----------------------------------------------------------
# Sun Proprietary/Confidential Code
# Copyright 2001, Sun Microsystems, Inc. All rights reserved.
# ----------------------------------------------------------
#</copyright>

use System;
use Util;
use PDM::ConfigFile;
use Modules;
use Matrix;
use Revision;
use Getopt::Std;
use strict;
use Process;

#
# runs locally, started from the GUI.
#
my(%opts);

sub usage {
  print <<EOF;
Usage: ras_revcheck -s [status] -p [print] -P [print errors] 
                    -h <hostname>    # will run revcheck on this host
                    -M <module_list|ALL> 
                    -T <tab delimited format>
                    -e <email> -m <matrix> 
                    -b [background, default is foreground] 
                    -l [display valid modules] 
EOF
}

if (!getopts("TPpblse:m:h:M:", \%opts)) {
    usage();
    exit(1);
}

#close(STDERR); close(SDTOUT); close(STDIN);

my $HOME    = System->home_dir();
my $RASPORT = System->getConfigPort($HOME);

System->set_home($HOME);
System->set_rasport($RASPORT);

my($renv, $devs, $hosts,$notifs) = PDM::ConfigFile->read;
System->set_renv($renv);

my $MODULES = $opts{M};
my $MATRIX  = $opts{m} || Matrix->defaultFile();
my $EMAIL   = $opts{e};
my $PRINTERR = $opts{P};
my $TABS     = $opts{T};
my $ID      = "Revision";
my @REPORTS;


if ($opts{l}) {
   &modules_list();
   exit;
}
if ($opts{s}) {
   my $st = Process->status($opts{h}, $ID);
   print "$st \n";
   exit;
}

my $done = 0;
if ($opts{M}) {
  my $st = Process->status($opts{h}, $ID);
  if ($st =~ /Running/) {
     print "Revision checking already running!\n";
     exit(1);
  }

  if($Process::ERROR =~ /Can't connect/){
    print "ERROR: $Process::ERROR \n";
    exit(1);
  }


  my $opts = "-M \"$MODULES\" " if ($MODULES);
  $opts   .= "-e \"$EMAIL\" "   if ($EMAIL);
  $opts   .= "-m $MATRIX "      if ($MATRIX);
  Process->run($opts{h}, "bin/ras_revcheck $opts", \&run, !$opts{b}, 60*60, \&printnew);
  $done = 1;
  $opts{p} = 1 if (!$opts{b});
}

if ($opts{p} || $opts{P}) {
   &printit($opts{h}, $ID, $opts{P});
  $done = 1;
}
if (!$done) {
  usage();
  exit(1);
}

sub printnew {
  my($new) = @_;
  # print $new;
}



sub modules_list {
   my $mods   = Modules->load("Revision");
   print "Modules: \n";
   foreach my $x (@$mods) {
        print "$x|";
   }
   print "\n";

}

sub run {
   my $LOG    = System->get_home() . "/DATA/tmp/${ID}_log";

   my $mailer = $renv->{mailer} || "/usr/bin/mail";
   my($acronym) = $renv->{GSV_ACRONYM};
   
   Process->start($ID);
   
   my ($env)      = Revision->hbas_present();
   my $matrix     = Matrix->read($MATRIX, $env);
   my $installedp = Revision->readInstalledPatches();
   
   my ($include, $errors);
   unlink $LOG;
   my @input_m = split(/\|/, $MODULES);
   if ( !$matrix )  {
         my $db = Revision->warning();
         push (@REPORTS, @$db);
         open(O, ">>$LOG"); print O "Revision check is  done\n"; close(O);
         $include = "";
   } else { 
      my $mods   = Modules->load("Revision");
      # check module name correctly input  from cmd line
      if ($MODULES ne "ALL") {
        foreach my $y (@input_m) {
            my $mod_ok =0;
            foreach my $z (@$mods) {
                if (( $y =~ /$z/i ) && ($z =~ /$y/i)) {
                  $mod_ok = 1 ;
                }
            }
            if (!$mod_ok) {
               my $valid_option; 
               foreach my $x (@$mods) {
                  $valid_option .="$x|";
               }
               print "The  module name: $y is not correct.\n Valid module are: $valid_option \n";
               exit;
            }
       } 
     }
     
     foreach my $x (@$mods) {
          if ($MODULES eq "ALL" || index(lc("|$MODULES|"), lc("|$x|")) >= 0) {
             $include .= " $x|";
             my $mod = "Revision::$x";
             my $db;
             eval {
               $db = $mod->RUN($matrix, $installedp);
             };
             if (!$db) {
               $db = Revision->warning2($x);
               push(@REPORTS, @$db);
             } elsif ($@) {
               $errors .= "ERROR in $mod: $@ \n";
             } else {
               push(@REPORTS, @$db);
             }
             open(O, ">>$LOG"); print O "module $x done\n"; close(O);
             chop($include);
          }
     }
   } 
   my $report;
   my $result;
   $report->{debug}  = 1;
   $report->{include}= $include;
   $report->{data}   = \@REPORTS;
   $report->{date}   = Util->get_today();
   $report->{errors} = $errors;
   $report->{matrix} = $MATRIX;
   
   my $text_report = &textReport($report);

   Process->write($report, $ID);
   
   if ($EMAIL) {
     Util->writef(System->get_home() . "/DATA/revision_email",$EMAIL);
     my $url  = Util->makeUrl($renv->{hostname}, "?GO=GUI::Revision::readLastReport");
   
     Util->run_command("$mailer $EMAIL", "mail", 10,
         { data => "From: $acronym\n".
                   "Subject: Revision Checking completed\n\n" .
                   "Revision Checking report,  Use Matrix: $report->{matrix} \n".
                   "Run on $renv->{hostname} \n\n$text_report"});
   }
   
   Process->done($ID);
}

sub printit {
  my($host, $ID, $error_only) = @_;
  my $R = Process->read($host, $ID);
  print $R->{errors};
  print &textReport($R, $host, $error_only);
}


sub textReport {
   my($report, $host, $error_only) = @_;
   my $result;
   my $FORMAT = "%-15.15s %-50.50s %-10.10s %-12s %-12s %-10s %-12s %-10s\n";
   $FORMAT = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" if ($TABS);
   my ($cnt, %KEY);

   my($renv, $devs) = PDM::ConfigFile->read();
   foreach my $d (@$devs) {
      $KEY{$d->{name}} = $d->{key};
      $KEY{$d->{ipno}} = $d->{key};
   }
   
   foreach my $ele (@{$report->{data}}){
      next if ($error_only && $ele->[2] eq "PASS");
      if (defined($ele)){
        if ($TABS) {
	  my $key = $KEY{$ele->[1]};
	  if (!$key){
	    my @N = split(/\./, $ele->[1]);
	    $key = $KEY{$N[0]};
	  }
          $ele->[1] = "$key\t$ele->[1]";  # insert the key in the tab report.
        }
        $result .= sprintf($FORMAT, @$ele);
        $cnt++;
      }
   }
   if (!$cnt) {
      if (!$host) {
        $host = "local host machine"; 
      }
      my @input_m = split(/\|/, $MODULES);
      my @re;
      my $ptr;
      my $info = "No this type of device is  present. Please check system set up";
      foreach my $y (@input_m) {
         @re = ($y, undef,'ERR',undef, undef, undef,undef,$info);
         $ptr = \@re;
         $result .= sprintf($FORMAT, @$ptr);
      }
   }
   my $title = sprintf($FORMAT, "Type", "Name","Status",
                "Curr_Ver","Expect_Ver","Curr_Patch", "Expect_Patch","Comments");
   if (!$TABS) {
     $title   .= sprintf($FORMAT, "================",
                "===========================================",
                "==========", "============", "============",
                "==========", "============", "==================");
   }
   
   return "$title\n$result\n";
}

