#!/usr/bin/perl 
#######################################################
# Script name:  patch_rpm
# Author:       Sergey Kryazhev
# Description:  This script aplies/undoes RPM kernel patches,
#               RPM application patches and aplies RPM vulnerability updates
# INPUT: $ARGV[0]   - can be -in/-out. Means action.(in - pins, out - poos)
#        $ARGV[1]   - RPM backup storage
#        $ARGV[2].. - RPM package filenames
# OUPUT: $OK    - OK
#        $ERROR - ERROR
# Date: February 2007
#######################################################

use lib "/opt/nortel/base/lib";

use strict;
use warnings;

use Getopt::Long;
use common_variables;
use patchutil::patches_target;
use patchutil::patches_public;
use install_common;
use base_system;
use baselog;
use CommonInstallUtils;

sub kernelUpdate($@);
sub installNortelRPM($@);
sub installSystemRPM($@);

sub actionRPM($@);
sub extractPkgName(@);
sub removeOrigRPMS(@);
sub skipBaseKernelRPM(@);

sub main();

exit(main());

sub main()
{
   my ($ret, $backupdir);
   our $opt_in  = $FALSE;
   our $opt_out = $FALSE;
   GetOptions('in', 'out');
   $backupdir = shift(@ARGV);
   if (!($opt_in || $opt_out) || scalar(@ARGV) == 0)
   {
      print <<HERE;
RPM package installer/uninstaller.
usage:
    patch_rpm <-in|-out> <backup directory> RPM list
    
    -in  install 
    -out uninstall 
HERE
      return $ERROR;
   } ## end if (!($opt_in || $opt_out...

   $ret = check_pkg($backupdir, @ARGV);

   if ($ret == $KERNEL_RPM)
   {
      return !kernelUpdate(($opt_in ? 'install' : 'erase'), @ARGV);
   }
   elsif ($ret == $SYSTEM_RPM)
   {
      return
        !(
          $opt_in
          ? updateSystemRPM('pins', @ARGV)
          : updateSystemRPM('poos', @ORIG_APP_RPMS)
         );
   }
   elsif ($ret == $NORTEL_RPM)
   {
      return
        !(
          $opt_in
          ? updateNortelRPM('pins', @ARGV)
          : updateNortelRPM('poos', @ORIG_APP_RPMS)
         );
   } ## end elsif ($ret == $NORTEL_RPM...
   return $ERROR;
} ## end sub main()

##############
#Description: skip kernel rpm for the BASE version ($first_ver variable) from the list
#INPUT:  @_ - rpm's list
#OUTPUT: @files - rpm's list
##############
sub skipBaseKernelRPM(@)
{
   my @files;
   foreach (@_)
   {
      /.*\/(.+)-(.+)-(.+)\.(.+)\.rpm$/;
      next if (("$2-$3" eq $FIRST_VER) && ($1 =~ /^kernel(-smp?)$/));
      push @files, $_;
   } ## end foreach (@_)
   return @files;
} ## end sub skipBaseKernelRPM(@)

#######
#Description: kernel update manipulation
#INPUT:  'install'/'erase' - install/uninstall kernel update , @files - kernel update rpm's
#OUTPUT: $TRUE  (1) - success
#	 $FALSE (0) - error
#######
sub kernelUpdate($@)
{
   my ($file, $inst, @files);
   $inst  = shift(@_);
   @files = @_;
   chomp(@files);
   my @actions = ('install', 'erase');

   #check action
   my %act = map {$_ => ''} @actions;
   return $FALSE if !defined(keys(%act));

   $inst  = ($inst eq $actions[0] ? $TRUE : $FALSE);
   @files = skipBaseKernelRPM(@files);

   if ($inst)  #installation
   {
      foreach $file (@files)
      {
         system("$RPM_COMMAND -qpi --nosignature $file 2>/dev/null");
         return $FALSE unless getYNResponse("Do you want to continue?", 'Y');
      }
   } ## end if ($inst)
   else        #uninstallation
   {
      @files = keys(%{extractPkgName(@files)});
   }

   #install new kernel
   $inst
     ? print "Performing new kernel installation...\n"
     : print "Performing uninstall kernel...\n";
   unless (actionRPM($inst ? 'install' : 'erase', @files))
   {
      baselog($LOG_ERROR, "The kernel " . ($inst ? "installation" : "uninstallation") . " is failed.\n");
      return $FALSE;
   }
   print "\nDone.\n";

   #chang_grub.conf
   print "Changing GRUB configuration...";
   if (system("$UPDATE_GRUB"))
   {
      baselog($LOG_ERROR, "Can not update GRUB configuration file.\n");
      return $FALSE;
   }
   print "Done\n";

   my $str = "The kernel " . ($inst ? "installation" : "uninstallation") . " is completed successfully.\n";
   baselog($LOG_INFO, $str);
   print $str;

   return $TRUE;
} ## end sub kernelUpdate($@)

#######
#Desription: rpm package actions
#INPUT:  'install'/'erase'/'upgrade'/'upg_old'/'upg_repkg' install/erase/upgrade/upgrade using --oldpackage option/
#        upgrade using --repackage option ,@files - rpm's list
#OUTPUT: $TRUE  (1) - success
#	 $FALSE (0) - error
#######
sub actionRPM($@)
{
   my ($file, $inst, @files);
   my %actions = (
                  'install'   => '-ihv ',
                  'erase'     => '-e',
                  'upgrade'   => '-Uhv',
                  'upg_old'   => '-Uhv --oldpackage --nomd5',
                  'upg_repkg' => '-Uhv --repackage',
                 );
   $inst = shift(@_);

   return $FALSE if !defined($actions{$inst});
   @files = @_;
   chomp(@files);
   system("$RPM_COMMAND $actions{$inst} --nosignature @files ");
   if ($? >> 8 ne 0)
   {
      baselog($LOG_ERROR, "Can not " . $inst . " @files.\n");
      return $FALSE;
   } ## end if ($? >> 8 ne 0)
   return $TRUE;
} ## end sub actionRPM($@)

#######
#Description: extract package names from rpm's
#INPUT:  %filenames - rpm packages filenames.
#        format: pkg_name-version-release => pkg_name
#OUTPUT: @filenames - packages names
#######
sub extractPkgName(@)
{
   my (@filenames);
   @filenames = `$RPM_COMMAND -qp --nosignature --qf '%{Name}-%{Version}-%{Release}\\n%{Name}\\n' @_ 2>/dev/null`;
   chomp(@filenames);
   return {@filenames};
} ## end sub extractPkgName(@)

#######
#Description:   Performs system RPM update
#INPUT:         'pins'/'poos' - install/uninstall rpm patch , @files - system rpm's
#OUTPUT:        $TRUE  (1) - success
#	        $FALSE (0) - error
#######
sub updateSystemRPM(@)
{
   my ($file, $inst, @files);
   $inst  = shift(@_);
   @files = @_;
   chomp(@files);
   my @actions = ('pins', 'poos');

   #check action
   my %act = map {$_ => ''} @actions;
   return $FALSE if !defined(keys(%act));

   $inst = ($inst eq $actions[0] ? $TRUE : $FALSE);

   #install SU
   $inst
     ? print "Performing SU installation (Linux OS RPM)...\n"
     : print "Performing SU uninstall (Linux OS RPM)...\n";

   #remove original RPM's from the file list
   @files = removeOrigRPMS(@files);
   #
   # If there are no RPM to process then skip install/uninstall
   if (scalar(@files) != 0)
   {
      unless (actionRPM($inst ? 'upg_repkg' : 'upg_old', @files))
      {
         baselog($LOG_ERROR, "The SU " . ($inst ? "installation" : "uninstallation") . " has failed.\n",$TRUE);
         return $FALSE;
      }
      print "\nDone.\n";

      if (not $inst) #uninstall
      {
         #delete old backup rpm since we no longer need it. We're running from it and can recreate it when needed
         if (!unlink (@files))
         {
            baselog($LOG_WARNING, "Unable to remove backup rpm\n");            
         }
      }
   }
   else
   {
      baselog($LOG_INFO, "No RPMs to " . ($inst ? "install" : "uninstall") . "\n", $TRUE);
   }
   baselog($LOG_INFO, "The SU " . ($inst ? "installation" : "uninstallation") . " has completed.\n",$TRUE);

   return $TRUE;
} ## end sub installRPMUpdate(@)

#######
#Description:   Performs Nortel RPM update
#INPUT:  'pins'/'poos' - install/uninstall rpm patch , @files - nortel rpm's
#OUTPUT: $TRUE  (1) - success
#	 $FALSE (0) - error
#######
sub updateNortelRPM($@)
{
   my ($file, $inst, @files);
   $inst  = shift(@_);
   @files = @_;
   chomp(@files);
   my @actions = ('pins', 'poos');

   #check action
   my %act = map {$_ => ''} @actions;
   return $FALSE if !defined(keys(%act));

   $inst = ($inst eq $actions[0] ? $TRUE : $FALSE);

   #install SU
   $inst
     ? print "Performing SU installation (Nortel RPM)...\n"
     : print "Performing SU uninstall (Nortel RPM)...\n";

   #remove original RPM's from the file list
   @files = removeOrigRPMS(@files);
   #
   # If there are no RPM to process then skip install/uninstall
   if (scalar(@files) != 0)
   {
      unless (actionRPM($inst ? 'upgrade' : 'upg_old', @files))
      {
         baselog($LOG_ERROR, "The SU " . ($inst ? "installation" : "uninstallation") . " has failed.\n",$TRUE);
         return $FALSE;
      }
      print "\nDone.\n";
   }
   else
   {
      baselog($LOG_INFO, "No RPMs to " . ($inst ? "install" : "uninstall") . "\n", $TRUE);
   }
   baselog($LOG_INFO, "The SU " . ($inst ? "installation" : "uninstallation") . " has completed.\n",$TRUE);

   return $TRUE;
} ## end sub RPMPatch($@)

#Description: removes original rpm's from the rpm's list
#INPUT:  @files -  rpm's
#OUTPUT: @files - rpm's list without original rpm's
sub removeOrigRPMS (@)
{
   my @files = ();
   foreach (@_)
   {
      if (system("$RPM_COMMAND -q `$RPM_COMMAND -qp --nosignature --qf '%{Name}-%{Version}-%{Release}' $_ ` >/dev/null 2>&1") >> 8)
      {
         push(@files, $_);
      }
      else
      {
         baselog($LOG_DEBUG, "The RPM package $_ is skipped from the list.");
      }

   } ## end foreach (@_)
   return @files;
} ## end sub removeOrigRPMS (@)

