#!/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 PPRO;
use Util;
use PDM::ConfigFile;
use Getopt::Std;
use strict;
use Process;

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

sub usage {
  print <<EOF;
Usage: ras_downgrade -s -U -p -S session_id -h
                    -U : Backout all patches installed in the previous session.
                    -S <session> , should be 'storade'
                    -s : status
                    -p : print report.
                    -h : Help.
                    -b : run background, default is foreground
Example:
       ras_downgrade -S storade -U -b

EOF
}

if (!getopts("S:sp:Ubh", \%opts) || $opts{h}) {
    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, $Config) = PDM::ConfigFile->read;
System->set_renv($renv);
if ($renv->{solution} eq "N") {
   print "Function not available yet outside of a Sun Solution product!\n";
   exit;
}
require Inventory;

my $PRINTERR = $opts{P};
#my $IPS      = $opts{i};
my $SID      = $opts{S};
my $ID      = "Downgrade";
my @REPORTS;

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

my $done = 0;
if ($opts{U}) {
  my $st = Process->status($opts{h}, $ID);
  if ($st =~ /Running/) {
     print "Revision Downgrade already running!\n";
     exit(1);
  }
  Process->run($opts{h}, "bin/ras_downgrade -U -S $SID", \&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}, $Config);
  $done = 1;
}
if (!$done) {
  usage();
  exit(1);
}

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

sub store_passwords {
  my $array_p = System->getPassword("array");
  my $D = "/opt/SUNWppro/lib";
  if ( -d $D) {
     for my $i (40,41,42,43,44,50,51,52,53,54,55) {
         open(W, ">$D/.192.168.0.${i}pw");
         print W "$array_p\n";
         close(W);
     }

     #my $array_p = System->getPassword("dsp");
     my $array_p = "sun1";
     for my $i (10) {
         open(W, ">$D/.192.168.0.${i}pw");
         print W "$array_p\n";
         close(W);
     }

  }


}

sub run {
   my $debug;
   &store_passwords();

   Process->start($ID);
   my $lock  = LockManager->new();
   my $locki = $lock->exists("system", 1) || {};
   my $date  = Util->get_today();
   my ($err_cnt, $REPORT);
   
   if ($locki->{info}) {
      # LOG to SUNWstade/log/cron_patch.log
      $debug = "$date Conflict, system already reserved: $locki->{info}\n";
      $err_cnt++; $REPORT = {};

   } else {

      my $mins = 6 * 60;  # 6 hours
      my $info = "revision_maintenance|ras_downgrade|Manual Downgrade|$date|$mins|$$";
      my $rc   = $lock->lock("system", 60*60*6, 0, $info);

      my $cli = PPRO->cli_path();

      my $LOG = System->get_home() . "/DATA/tmp/Downgrade.log";

      my $command;




      $command = "$cli -s $SID -U >$LOG 2>&1";

      $debug .= "Running patch backout:\n";

      my($err, $out)= Util->run_command($command, "test", 100*60*60); # 100 hour timeout
      my $ppro = PPRO->parseFromFile("/var/tmp/pprosvc_$SID/undo_patches.xml");

      # Errors can occur during upgrade
      if ($ppro->{ERRORS}) {
          $err_cnt++; # Top level errors
      } else {
        foreach my $dev (@{$ppro->devices()}) {
           foreach my $patch (@{$dev->patches()}) {
	        # errors at patch level
                $err_cnt++ if ($patch->{error});
           }
	}
      }
      if ($ppro) {
         if (!$REPORT) {
            $REPORT = $ppro;
         } else {
            foreach my $k (keys %$ppro) {
              $REPORT->{$k} = $ppro->{$k};
            }
         }
      }
   
      if (open(OO, $LOG)) {
      	my $l;
      	while ($l = <OO>) {
         $debug .= $l;
      	}
      	close(OO);
      }		
   }
   

   my ($result, $report);
   $report->{debug}  = 1;
   $report->{error_cnt}  = $err_cnt;
   $report->{data}   = {trace => $debug, report => $REPORT};
   $report->{display_method} = "Service::Upgrade::reportDown";
   $report->{date}   = Util->get_today();
   Process->write($report, $ID);
   Inventory->upgradeMaserati() if (!$err_cnt);

   sleep(30);
   $lock->unlock("system");

   Process->done($ID);
   Process->email($report, "Solution Backout");
}

sub printit {
  my($host, $ID, $error_only, $Config) = @_;
  
  my $R = Process->read($host, $ID);

  my $devs = $Config->devices();

  my $ppro = PPRO->parse($R->{data}{report});
  my $stdout = $R->{data}{trace};
  my $out = "$stdout";
  $out =~ s/\.\.+/\.\n/g;
  print "TRACE:\n======\n$out\n";

  # Not equired in StorADE 2.4
  #if ($PPRO::ERROR) {
  #   print "Error: Patch Pro Error\n";
  #   return;
  #}

  if ($ppro->{ERRORS}) {
     print "Error: ppro->{ERRORS}\n";
     return; 
  }

  my %IP;  # map devices by ipno
  foreach my $d (@$devs) {
     $IP{$d->{ipno}} = $d;
  }

  my $LB = Labels->read("Service::Upgrade");
  print "\nPATCH BACKOUT REPORT:";
  print "\n====================\n";

  foreach my $pp (@{$ppro->devices()}) {
      my $inv_d = $IP{$pp->key()};
      my $ip   = $pp->key();
      my $name = $inv_d->{name};
      my $type = lc($pp->type());
      my $dev  = $Config->deviceByIP($ip);
      my ($label, $k, $sev, $info);
      $sev = 0;
      if ($type eq "sunos") {
        $label = $LB->{sp};
        $k     = "host:" . $renv->{hostname};
      } elsif ($dev) {
        $label = "$dev->{type}: $dev->{name}";
        $k     = "$dev->{type}:$dev->{key}";
      } elsif ($name) {
        $label = "$type:$name";
      } else {
        $label = "$type:UNKNOWN";
      }
      my $P = $pp->patches();
      my $pcnt = $#$P +1;
      my $t2 = $LB->{patches};
      print "\n $label: $pcnt patch(es). \n";
      my $cnt;
      foreach my $patch (@$P) {
         my $pid = $patch->{patchID};
         my $syn = $patch->{synopsis};
         my $err = $patch->{error};
         my $frus;
         foreach my $fru (@{$patch->frus()}) {
            $frus .= "$fru->{locator}, ";
         }
         if ($frus) {
            chop($frus); chop($frus);
         }
         my $err2 = "   Message: $err \n" if ($err);

         print "   PatchID: $pid \n";
         my $t1 = $syn;
         $t1 .= " " if ($syn && $err2);
         $t1 .= $err2;
         $t1 .= "      Frus: $frus\n" if ($frus);
         print "$t1 \n";
         $cnt++;
      }
  } 

}

