#!/usr/bin/perl
###############################################################################
## @file   pPoos
# @brief   Perform de-activating bundle of patches passed from Patch Manager
# @details This utility provides the interface for de-activating bundle of patches.
#          This interface is intended *only* for Patch Manager, so, it should
#          not be user friendly. The amin difference from the standard poos
#          is that, the new interface can operate with the bundle.
# @note    If you change this module please change the corresponding subroutine
#          in base_pm module.
# @author Ilya Kudelin
# @author Natalya Patselya
# @author Alexander Kolotov
# @version 1.00 - Initial version
# @version 1.01 - Modified to ensure patch ordering as specified on the input
#                 line is maintained
# @version 1.02 - New option 'context' has been added.

use warnings;
use strict;

use common_variables;
use common_functions;
use baselog;
use patchutil::patching;
use patchutil::patches_target;
use Getopt::Long;
use base_semctl;

## @skipline
sub pPoos();  #<- default entry point
## @skipline
sub cleanup();

my $semmngr;
my @sem_list                  = ($SEM_PATCH, $SEM_APPSTART, $SEM_HARD);
my $ssh_hang_on_exit_bug_flag = $FALSE;                                 # NEEDED BY END FUNCTION

exit(pPoos());

###############################################################################
## @fn sub pPload()
# @brief   Main entry point
# @details This subroutines uses patching object to perform patch de-activating for
#          bundle of patches. It prepares the output for processing it by Patch
#          Manager side.
# @return  OK - the patches are de-activated successfully
# @return  ERROR - Some error happens
sub pPoos()
{
   set_subsystem('Base_Patch');

   if (warning_if_not_nortel_grp())
   {
      return $ERROR;
   }

   my $patch_str;
   my $res = GetOptions("patches:s" => \$patch_str, "die" => \$ssh_hang_on_exit_bug_flag);
   if (!$res)
   {
      print "Incorrect options provided\n";
      print_pod_usage();
      return $ERROR;
   } ## end if (!$res)

   baselog($LOG_INFO, "pPoos command is invoked for patches '$patch_str'");

   my %patches = map {$_ => $pERROR} split(/,/, $patch_str);

   #
   # Originally "keys %patches" was used to extract the patches to process but
   # "The keys are returned in an apparently random order. The actual random order
   # is subject to change in future versions of perl" and thus we will use an array
   # to ensure that the patch order specified by the input parameters are maintained.
   #
   # PM has been designed to ensure that the correct SU & Patch order is specified.
   #
   my @patches = split(/,/, $patch_str);

   signals_ignore();

   $semmngr = base_semctl::new("PATCH");
   if (!defined($semmngr))
   {
      my $error_descr = $!;
      baselog($LOG_ERROR, "Cannot create semaphore manager object ($error_descr).");
      return $ERROR;
   } ## end if (!defined($semmngr)...
   if (!$semmngr->sem_take(\@sem_list, $WAIT_FLAG, $PINS_SEM_WAITTIME))
   {
      baselog($LOG_ERROR, "Cannot take semaphores.");
      baselog($LOG_ERROR, "patching operation aborted.\n");
      undef $semmngr;
      return $ERROR;
   } ## end if (!$semmngr->sem_take...

   my $patching = patchutil::patching::new();
   if (not defined $patching)
   {
      baselog($LOG_ERROR, "Cannot create object 'patching'");
      cleanup();
      return $ERROR;
   } ## end if (not defined $patching...

   #poos
   baselog($LOG_INFO, "pPoos is invoked for patches: '" . join(' ', @patches) . "'");
   my $retval = $OK;
   foreach my $pname (@patches)
   {
      print "\n$PATCH_str $pname\n";
      print STDERR "\n$PATCH_str $pname\n";

      #actions

      my $patchID = $patching->{'DB'}->get_patch_id_by_name($pname);
      if (not defined $patchID)
      {
         baselog($LOG_ERROR, "Patch '$pname' is not installed", $TRUE);
         $patches{$pname} = $pERROR;
         $retval          = $ERROR;
         $patchID         = '-1';
      } ## end if (not defined $patchID...
      else
      {

         # Reset parameters to default every time in order to get rid of usage old
         # parameters
         my %params = ('interact' => $FALSE, 'pid' => $patchID, 'all' => $FALSE, 'sp' => $FALSE, 'filename' => undef, 'context' => 'PM');
         if ($patching->poos(\%params))
         {
            baselog($LOG_INFO, "Patch '$pname' was successfully put out of service");
            $patches{$pname} = $pOK;
         }
         else
         {
            baselog($LOG_ERROR, "Cannot put '$pname' out of service", $TRUE);
            $patches{$pname} = $pERROR;
            $retval = $ERROR;
         } ## end else [ if ($patching->poos(\%params...
      } ## end else [ if (not defined $patchID...
      print "\n$STATUS_str $patches{$pname} $patchID\n";
      print "\n$PM_SEPARATOR\n";
      print STDERR "\n$PM_SEPARATOR\n";
   } ## end foreach my $pname (@patches...

   undef $patching;
   if (not cleanup())
   {
      return $ERROR;
   }
   return $retval;
} ## end sub pPoos()

###############################################################################
## @fn sub cleanup()
# @brief   Releases semaphores
# @details None
# @return  TRUE - semaphores released successfully
# @return  FALSE - Some error happens
sub cleanup()
{
   my $retval = $TRUE;
   if (!$semmngr->sem_give(\@sem_list))
   {
      baselog($LOG_ERROR, "Cannot release semaphores.");
      $retval = $FALSE;
   }
   undef $semmngr;
   return $retval;
} ## end sub cleanup()

END
{  # WORKAROUND - YUK!
     #
     #   Due to a OpenSSH hang-on-exit issue, if we are being called remotely we
     #   will create and call a script to kill our parent "sshd: nortel@notty"
     #   to terminate the ssh session on this side of a remote ssh reguest
     #   session
     #
   if ($ssh_hang_on_exit_bug_flag)
   {

      # Save original return value
      my $retVal = $?;

      if (ssh_hang_on_exit_bug() == $ERROR)
      {
         return $ERROR;
      }

      baselog($LOG_INFO, "I AM OUTA HERE");

      # Return the original return value since "ssh_hang_on_exit_bug" would
      # have changed the result.
      return $retVal;
   } ## end if ($ssh_hang_on_exit_bug_flag...
}  # END
