#!/usr/bin/perl
###################################################################################
## @file   pPins                                       
# @brief   Perform activating bundle of patches passed from Patch Manager
# @details This utility provides the interface for 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 pins
#          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 Nataliya 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

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 pPins();  #<- 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(pPins());

######################################################################################
## @fn sub pPins()                                             
# @brief   Main entry point                                     
# @details This subroutines uses patching object to perform activating for
#          bundle of patches. It prepares the output for processing it by Patch
#          Manager side.                                        
# @return  OK - the patches are activated successfully             
# @return  ERROR - Some error happens
sub pPins()
{
   
   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, "pPins 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...

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

      my $patchID = $patching->{'DB'}->get_patch_id_by_name($pname);
      if (not defined $patchID)
      {
         baselog($LOG_ERROR, "Patch id is undefined for '$pname'", $TRUE);
         $patches{$pname} = $pERROR;
         $patchID         = '-1';
         $retval          = $ERROR;
      } ## 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);
         if ($patching->pins(\%params))
         {
            baselog($LOG_INFO, "patch '$pname' was successfully put in service");
            $patches{$pname} = $pOK;
         }
         else
         {
            baselog($LOG_ERROR, "patch '$pname' cannot be put in service");
            $patches{$pname} = $pERROR;
            $retval = $ERROR;
         } ## end else [ if ($patching->pins(\%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...

   baselog($LOG_INFO, "pPins command finished");  

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

#################################################################
## @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
