#!/usr/bin/perl 
###############################################################################
## @file   sudo_nortel
# @brief   Wrapper script
# @details This script provides specific actions that requires root privileges.
# @author Kate Bereznyakova
# @author Evgeniy Lazarev
# @author Petr Kascheev
# @version 1.00 - Initial version
# @version 1.01 - app_service function is reworked in order to
#                 use base_apps_service methods
# @version 1.10 - app_service function is reworked to support management of
#                 the Nortel and Base Applications separately.
# @version 1.11 - function is added - reapply_basic_hardening_post_patching
# @version 1.20 - dhcpd_config and if_ctrl actions are added by Alex Arkhipov
# @version 1.21 - Two colons were removed before shared functions and variables.
# @version 1.22 - refresh_udev() function is removed.
# @version 1.23 - sftp_login() function has been added.
# @version 1.24 - "arping" added after new interface adding
# @version 1.25 - app_service() function changed to invoke 'app_call' function if application name is provided
# @version 1.26 - time_setup function is added.
# @version 1.27 - sftp_login has been rewritten
# @version 1.28 - cleanup_patchdir function is added for new key $CLEANUP_PATCHDIR.
# @version 1.29 - execute_scripts was updated. New variables were added.
#   @li NONINTERACTIVE
#   @li BACKUP_ERR_MODE
#                 There are shared variables from recovery::backup. If these are not transmitted, set into FALSE.
# @version 1.30 - function is added - reapply_enhanced_hardening_post_patching.
# @version 1.31 - "send GARP packet" procedure moved to the function send_arp_update(). send GARP packet even if interface is up.
# @version 1.32 - new create_usb_mountpoint() is added
# @version 1.33 - function patching_chown() and patching_chmod() have been added.
# @version 1.34 - update_hosts function is added.
# @version 1.35 - app_service() function changed to invoke 'app_management' function (instead of 'app_call') when an application
#                 name is provided to ensure that the firewall is restarted accordingly
# @version 1.36 - replace_ntp_configs function was added

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

use warnings;
use strict;
use Switch;

use common_variables;
use common_functions;
use baselog;
use recovery::backup;
use base_apps_service;
use base_ftp;
use base_semctl;
use base_system;
use hardening::hardening_common;
use baseParams;
use patchutil::patches_target;
use patchutil::patching;
use patchutil::patches_public;

sub main();
sub clear_backup();
sub cleanup_patchdir();
sub app_service(@);
sub execute_scripts(@);
sub dhcpd_config(@);
sub is_if_up($);
sub sftp_login(@);
sub send_arp_update(@);
sub create_usb_mountpoint();
sub patching_chown($);
sub patching_chmod($$);
sub update_hosts($$);
sub replace_ntp_configs();

my %hash_functions = (
                      $CLEAR_BACKUP                             => \&clear_backup,
                      $APP_SERVICE                              => \&app_service,
                      $EXECUTE_SCRIPTS                          => \&execute_scripts,
                      $APP_DEPLOY                               => \&app_deploy,
                      $DHCPD_CONFIG                             => \&dhcpd_config,
                      $BASIC_HARDENIG_REAPPLY_POST_PATCHING     => \&reapply_basic_hardening_post_patching,
                      $ENHANCED_HARDENING_REAPPLY_POST_PATCHING => \&reapply_enhanced_hardening_post_patching,
                      $IF_CTRL                                  => \&if_ctrl,
                      $SFTP_LOGIN                               => \&sftp_login,
                      $TIME_SETUP                               => \&time_setup,
                      $CLEANUP_PATCHDIR                         => \&cleanup_patchdir,
                      $CREATE_USB_MOUNTPOINT                    => \&create_usb_mountpoint,
                      $PATCH_CHOWN                              => \&patching_chown,
                      $PATCH_CHMOD                              => \&patching_chmod,
                      $UPDATE_HOSTS                             => \&update_hosts,
                      $REPLACE_NTP_CONFIGS                      => \&replace_ntp_configs
                     );

my $DHCPD = 'dhcpd';

exit(main());

######################################################
#
# This is the main procedure
#
# Input: Key - parameter that defines required action
#
# Output: None
#
# Return: $OK
#         $ERROR
######################################################
sub main()
{
   my $retval = $ERROR;
   if (!defined(@ARGV))
   {
      baselog($LOG_ERROR, "Required parameter is missing.\n", $TRUE);
   }
   else
   {
      my $parameters = join(',', @ARGV);
      baselog($LOG_DEBUG, "Incoming parameters are: $parameters.");

      my $func = shift @ARGV;
      if (exists $hash_functions{$func})
      {
         $retval = $hash_functions{$func}->(@ARGV);
      }
      else
      {
         baselog($LOG_ERROR, "Incorrect parameter " . $func . " provided.\n", $TRUE);
      }
   } ## end else [ if (!defined(@ARGV))
   return $retval;
} ## end sub main()

###----------------------------------------------------------------------------
#
#  Clean backup directory.
#
#  Input:  none
#  Return: $OK    (0) - no errors
#          $ERROR (1) - error confition.
###----------------------------------------------------------------------------
sub clear_backup()
{
   if (system("$RM -rf $BACKUPDIR/*") != 0)
   {
      baselog($LOG_ERROR, "Cannot clean up $BACKUPDIR directory.\n", $TRUE);
      return $ERROR;
   }
   return $OK;
} ## end sub clear_backup()

############################################################
## @fn sub cleanup_patchdir()
# @brief Cleanup $PATCHDIR and $SRV_PACK_DIR files and subdirectories
# @      created during previous patching activities.
# @details 1. Cleanup all the files inside $PATCHDIR
# @        2. Remove and re-generate $HANDLES
# @        3. Remove /fur/bin/war/tap patchdir subdirectories if
# @        exist.
# @        4. Cleanup content of $SPECINS dir.
# @        5. Cleanup content of $REVERT dir.
# @        6. Cleanup $SP_REVERT_DIR if exists.
# @        7. Cleanup $SPINS_DIR if exists.
# @        8. Cleanup $SPLOAD_DIR if exists..
# @        9. Cleanup all the files under $SRV_PACK_DIR directory.
# @return $OK - cleanup sucessful.
# @return $ERROR - error occurred during cleanup.
#############################################################
sub cleanup_patchdir()
{
   my $ret_val;  # ret_val value from do_system

   baselog($LOG_INFO, "Starting $PATCHDIR cleanup.\n", $TRUE);

   # remove all patches from $PATCHDIR
   if (system("$RM -f $PATCHDIR/*.$PATCHEXT"))
   {
      baselog($LOG_ERROR, "Cannot remove patches from $PATCHDIR directory.\n", $TRUE);
      return $ERROR;
   }

   # remove all text files from $PATCHDIR (ex. MIRCC.txt)
   if (system("$RM -f $PATCHDIR/*.txt"))
   {
      baselog($LOG_ERROR, "Cannot remove text files from $PATCHDIR directory.\n", $TRUE);
      return $ERROR;
   }

   # remove fru/war/bin/tap subdirectories inside $PATCHDIR if exist
   if (-d "$PATCHDIR/fru")
   {
      if (!do_system([$RM, "-rf", "$PATCHDIR/fru"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $PATCHDIR/fru directory ($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end if (-d "$PATCHDIR/fru"...
   if (-d "$PATCHDIR/war")
   {
      if (!do_system([$RM, "-rf", "$PATCHDIR/war"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $PATCHDIR/war directory ($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end if (-d "$PATCHDIR/war"...
   if (-d "$PATCHDIR/bin")
   {
      if (!do_system([$RM, "-rf", "$PATCHDIR/bin"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $PATCHDIR/bin directory ($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end if (-d "$PATCHDIR/bin"...
   if (-d "$PATCHDIR/tap")
   {
      if (!do_system([$RM, "-rf", "$PATCHDIR/tap"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $PATCHDIR/tap director y($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end if (-d "$PATCHDIR/tap"...

   # end of removing fru/war/bin/tap subdirectories inside $PATCHDIR if exist

   # remove content from $SPECINS directory
   if (system("$RM -rf $SPECINS_DIR/*"))
   {
      baselog($LOG_ERROR, "Cannot remove content from $SPECINS_DIR directory.\n", $TRUE);
      return $ERROR;
   }

   # remove content from $REVERT directory
   if (system("$RM -rf $REVERT_DIR/*"))
   {
      baselog($LOG_ERROR, "Cannot remove content from $REVERT_DIR directory.\n", $TRUE);
      return $ERROR;
   }
   if (-d $SP_REVERT_DIR)
   {
      if (!do_system([$RM, "-rf", "$SP_REVERT_DIR"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $SP_REVERT_DIR directory ($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end if (-d $SP_REVERT_DIR)
   if (-d $SPLOAD_DIR)
   {
      if (!do_system([$RM, "-rf", "$SPLOAD_DIR"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $SPLOAD_DIR directory ($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end if (-d $SPLOAD_DIR)
   elsif (-d $SPINS_DIR)
   {
      if (!do_system([$RM, "-rf", "$SPINS_DIR"], {$dsRETVAL => \$ret_val}))
      {
         baselog($LOG_ERROR, "Cannot cleanup $SPINS_DIR directory ($ret_val).\n", $TRUE);
         return $ERROR;
      }
   } ## end elsif (-d $SPINS_DIR)

   # remove all files from $SP directory
   if (system("$RM -rf $SRV_PACK_DIR/*"))
   {
      baselog($LOG_ERROR, "Cannot remove $SRV_PACK_DIR directory content.\n", $TRUE);
      return $ERROR;
   }
   baselog($LOG_INFO, "Finished $PATCHDIR cleanup.\n", $TRUE);
   return $OK;
}  # end sub cleanup_patchdir()

##############################################################################
#
# Operations with applications
# Note: APP_START semaphore must be taken before this function invoking
# Input: startup parameter ($SRV_START, $SRV_STOP, $SRV_STATUS,
#        $SRV_RESTART, $BASE_APPS)
# Return: result of execution of appstartup command.
#
##############################################################################
sub app_service(@)
{
   my $retval = $OK;
   my @params = @_;
   my $action = undef;
   if (scalar(@params) == 0)
   {
      baselog($LOG_ERROR, "Not enough parameters provided.\n", $TRUE);
      $retval = $ERROR;
   }
   else
   {
      if ($params[0] =~ /^($SRV_START|$SRV_STOP|$SRV_STATUS|$SRV_RESTART|$BASE_APPS)$/)
      {
         if (base_semctl::sem_test("SEM_APPSTART"))
         {
            baselog($LOG_ERROR, "appstart semaphore is free. Cannot continue appstart operation.");
            return $ERROR;
         }
         my $app = undef;
         if ($params[0] eq 'baseapps')
         {
            $app = new base_apps_service({$APPL_TYPE => $TYPE_BASE_APPL});
            shift(@params);
         }
         else
         {
            $app = new base_apps_service({$APPL_TYPE => $TYPE_NORTEL_APPL});
         }
         $action = shift(@params);
         unless (defined $app)
         {
            baselog($LOG_ERROR, "Can not create base_apps_service object");
            $retval = $ERROR;
         }
         else
         {
            my $app_name = shift(@params);
            if (defined $app_name)
            {
               my @args = ($app_name, $action);
               unless ($app->app_management(\@args))
               {
                  baselog($LOG_ERROR, "Action $action for application $app_name failed\n", $TRUE);
                  $retval = $ERROR;
               }
            } ## end if (defined $app_name)
            elsif ($action eq $SRV_RESTART)
            {

               unless ($app->stop())
               {
                  baselog($LOG_ERROR, "Applications can not be stopped\n", $TRUE);
                  $retval = $ERROR;
               }
               unless ($app->start())
               {
                  baselog($LOG_ERROR, "Applications can not be started\n", $TRUE);
                  $retval = $ERROR;
               }

            } ## end elsif ($action eq $SRV_RESTART...
            elsif (!$app->$action)
            {
               baselog($LOG_ERROR, "Cannot perform $action applications.\n", $TRUE);
               $retval = $ERROR;
            }
         } ## end else
         undef $app;
      } ## end if ($params[0] =~ /^($SRV_START|$SRV_STOP|$SRV_STATUS|$SRV_RESTART|$BASE_APPS)$/...
      else
      {
         baselog($LOG_ERROR, "Incorrect parameter " . $params[0] . " provided.\n", $TRUE);
         $retval = $ERROR;
      }
   } ## end else [ if (scalar(@params) ==...
   return $retval;
} ## end sub app_service(@)

###############################################################################
#
# @fn execute_scripts($section_name,$NONINTERACTIVE,$BACKUP_ERR_MODE)
# @brief Execution of scripts in specified section of "configure.xml"
# @param $section_name - section name of "configure.xml" files.
# @param $NONINTERACTIVE - execution mode($TRUE means NONinteractive)
# @param $BACKUP_ERR_MODE - check scripts exit status or not in
#                 execute_section_scripts(). Applicable only for
#                 noninteractive mode. If set into FALSE wxit status will be ignored
#                 and 'execute_section_scripts' will returns TRUE even some scripts fails.
# @return $ERROR - if at least one script failes
# @return $OK - otherwise
##############################################################################
sub execute_scripts(@)
{
   my $retval       = $ERROR;
   my $section_name = shift(@_);
   $NONINTERACTIVE  = shift @_;  #if set into true, actions will be executed in NONinteractive mode
   $BACKUP_ERR_MODE = shift @_;  #if set into false, if any script from $section_name will fail TRUE will be returned
                                 #else real state of executen will be returned.

   $NONINTERACTIVE  = $FALSE if (not defined $NONINTERACTIVE);
   $BACKUP_ERR_MODE = $FALSE if (not defined $BACKUP_ERR_MODE);

   if (!defined($section_name))
   {
      baselog($LOG_ERROR, "Not enough parameters provided.\n");
   }
   else
   {
      if (execute_section_scripts($section_name)) {$retval = $OK;}
   }
   return $retval;
} ## end sub execute_scripts(@)

##############################################################################
#
# Execution of appinstall script
# Input: $key - appinstall command key
#        $dir - deployment directory
# Return: $out - output value of appinstall script
#
##############################################################################
sub app_deploy($;$)
{
   my ($key, $dir) = @_;
   my $out = $ERROR;
   if (!defined $key)
   {
      baselog($LOG_ERROR, "Appinstall command key is undefined.\n");
      $key = '';
   }
   if (!defined $dir)
   {
      baselog($LOG_WARNING, "Deployment directory is undefined.\n");
      $dir = '';
   }
   unless (do_system([$APPINSTALL, $key, $dir], {$dsRETVAL => \$out}))
   {
      baselog($LOG_ERROR, "Cannot execute $APPINSTALL  successfully.\n");
   }
   return $out;
} ## end sub app_deploy($;$)

##############################################################################
# @fn dhcpd_config
# @brief Start, stop, restart DHCPD server.
# @details Copy dhcpd.conf file to /etc/ folder in case of start and restart
# @param $cmd - command to execute (start/stop/restart)
# @param $dhcp_conf - full path to dhcpd.conf file
# @return $OK - dhcpd action success
# @return $ERROR - error executing action
##############################################################################
sub dhcpd_config(@)
{
   my ($cmd, $dhcp_conf) = @_;
   my $retval = $OK;

   if (not defined($cmd))
   {
      baselog($LOG_ERROR, 'Command is not provided.');
      return $ERROR;
   }

   if (($cmd eq $SRV_START) or ($cmd eq $SRV_RESTART))
   {

      # Copy dhcp_conf file
      if (not defined($dhcp_conf))
      {
         baselog($LOG_INFO, 'The dhcp.conf file is not provided');
      }
      elsif (!-e $dhcp_conf)
      {
         baselog($LOG_ERROR, 'The dhcp.conf file does not exist:' . $dhcp_conf);
         return $ERROR;
      }
      else
      {

         # Copy new dhcp.conf file to /etc/ folder if dhcp.conf file provided
         unless (do_system([$CP, '-rf', $dhcp_conf, '/etc/']))
         {
            baselog($LOG_ERROR, "Cannot copy $dhcp_conf file to /etc directory");
            return $ERROR;
         }
         baselog($LOG_INFO, "The $dhcp_conf file was copied successfuly");
      } ## end else [ if (not defined($dhcp_conf...
   } ## end if (($cmd eq $SRV_START...
   elsif ($cmd ne $SRV_STOP)
   {
      baselog($LOG_ERROR, 'Unknown DHCPD_CONFIG command provided:' . $cmd);
      return $ERROR;
   }

   my $status = get_status_linux_service($DHCPD);
   if (($cmd eq $SRV_START) and ($status))
   {
      baselog($LOG_INFO, 'Service is already running. No need to start');
      return $OK;
   }
   elsif (($cmd eq $SRV_STOP) and (not $status))
   {
      baselog($LOG_INFO, 'Service is already stopped. No need to stop');
      return $OK;
   }

   baselog($LOG_DEBUG, "Executing command: $SERVICE $DHCPD $cmd");
   unless (do_system([$SERVICE, $DHCPD, $cmd]))
   {
      baselog($LOG_ERROR, 'Error executing dhcpd command:' . $cmd);
      $retval = $ERROR;
   }
   return $retval;
} ## end sub dhcpd_config(@)

##############################################################################
#
# @fn if_ctrl
# @brief controls creation/removal virtual interface
# @param $cmd - command to execute ($IF_UP/$IF_DOWN)
# @param $if_name - name of virtual interface
# @param $if_ip - ip address of virtual interface
# @param $if_bcst - broadcast ip address of virtual interface
# @param $if_msk - netmast of virtual interface
# @return $OK - action success
# @return $ERROR - error executin action
##############################################################################
sub if_ctrl(@)
{
   my $cmd     = shift(@_);
   my $if_name = shift(@_);
   my $retval  = $OK;
   my ($if_ip, $if_bcst, $if_msk);

   if (not defined($cmd))
   {
      baselog($LOG_ERROR, 'Command is not provided.');
      return $ERROR;
   }
   elsif (not defined($if_name))
   {
      baselog($LOG_ERROR, 'Interface name if not provided');
      return $ERROR;
   }

   my $sys_cmd = [$IFCONFIG, $if_name];

   if (($cmd eq $IF_UP))
   {
      if (scalar(@_) != 3)
      {
         baselog($LOG_ERROR, 'IF_UP: Incorrect number of arguments:' . scalar(@_));
         return $ERROR;
      }
      ($if_ip, $if_bcst, $if_msk) = @_;
      push(@{$sys_cmd}, ($if_ip, 'broadcast', $if_bcst, 'netmask', $if_msk, 'up'));
   } ## end if (($cmd eq $IF_UP))
   elsif ($cmd eq $IF_DOWN)
   {
      push(@{$sys_cmd}, 'down');
   }
   else
   {
      baselog($LOG_ERROR, 'Unknown IF_CTRL command provided:' . $cmd);
      return $ERROR;
   }

   my $status = is_if_up($if_name);
   if (($cmd eq $IF_UP) and ($status))
   {
      send_arp_update($if_name, $if_ip);
      baselog($LOG_INFO, $if_name . ' is already up.');
      return $OK;
   } ## end if (($cmd eq $IF_UP) and...
   elsif (($cmd eq $IF_DOWN) and (not $status))
   {
      baselog($LOG_INFO, $if_name . ' is already down.');
      return $OK;
   }
   baselog($LOG_DEBUG, 'Executing command: ' . join(' ', @{$sys_cmd}));
   unless (do_system($sys_cmd))
   {
      baselog($LOG_ERROR, 'Error executing command');
      $retval = $ERROR;
   }
   elsif ($cmd eq $IF_UP)
   {
      send_arp_update($if_name, $if_ip);
   }

   return $retval;
} ## end sub if_ctrl(@)

##############################################################################
# @fn is_if_up
# @brief check whether netwokr interface is up or not
# @param $if_name - name of virtual interface
# @return $TRUE - interface is up
# @return $FALSE - inteerface is down
##############################################################################
sub is_if_up($)
{
   my $if_name = shift(@_);
   if (not defined($if_name))
   {
      baselog($LOG_ERROR, 'Interface name is not provided');
      return $FALSE;
   }

   my @out = '';  # ifconfig command output container

   do_system([$IFCONFIG, $if_name], {$dsOUT => \@out});
   my @match = grep(/inet addr/, @out);
   if (scalar(@match))
   {
      baselog($LOG_DEBUG, "Interface $if_name is up");
      return $TRUE;
   }
   baselog($LOG_DEBUG, "Interface $if_name is down");
   return $FALSE;
} ## end sub is_if_up($)

###############################################################################
## @fn reapply_basic_hardening_post_patching()
# @brief   Reapply Basic hardening items.
# @details This method reapplies all Basic hardening modules. The method should
#          be invoked after patching operation(pins/poos).
# @return  OK  - the action is performed
# @return  ERROR - some error happens
sub reapply_basic_hardening_post_patching()
{

   # Reapply basic hardening items
   if (not do_basic_hardening_action($H_IF_POST_PATCHING))
   {
      baselog($LOG_ERROR, "Basic hardening items reapplying failed.");
      return $ERROR;
   }
   return $OK;
} ## end sub reapply_basic_hardening_post_patching()

###############################################################################
## @fn reapply_enhanced_hardening_post_patching()
# @brief   Reapply enhanced hardening items.
# @details This method reapplies all enhanced hardening modules. The method should
#          be invoked after patching operation(pins/poos).
# @return  OK  - the action is performed
# @return  ERROR - some errors happened
sub reapply_enhanced_hardening_post_patching()
{

   # Reapply enhanced hardening items
   if (not do_enhanced_hardening_action($H_IF_POST_PATCHING))
   {
      baselog($LOG_ERROR, "Enhanced hardening items reapplying failed.");
      return $ERROR;
   }
   return $OK;
} ## end sub reapply_enhanced_hardening_post_patching()

###############################################################################
## @fn sub sftp_login($user, $home)
# @brief   Perfors action before user logins via SFTP.
# @details Start sftp-server for specified user and put in jail.
# @param   $user - name of the loggining user.
# @return  OK - operations successfully completed.
# @return  ERROR - some error happened.
sub sftp_login(@)
{
   if (scalar(@_) != 1)
   {
      baselog($LOG_ERROR, "Incorrect number of parameters.");
      return $ERROR;
   }
   my ($user) = (@_);
   my $retval = $OK;
   my $home   = (getpwnam($user))[7];
   if (defined($home))
   {
      if (base_ftp::is_all_directories_mounted($user))
      {
         if (system("$CHROOT $home $RUNUSER $user -c \"$SFTPSERVER\""))
         {
            baselog($LOG_ERROR, "Can not start sftp-server for user '$user'.");
            $retval = $ERROR;
         }
         else
         {
            baselog($LOG_DEBUG, "sftp-server started for user '$user'.");
         }
      } ## end if (base_ftp::is_all_directories_mounted...
      else
      {
         baselog($LOG_INFO, "Not all the directories mounted for user '$user'.");
         $retval = $ERROR;
      }
   } ## end if (defined($home))
   else
   {
      baselog($LOG_ERROR, "Home directory for user '$user' is not defined.");
      $retval = $ERROR;
   }
   return $retval;
} ## end sub sftp_login(@)

###############################################################################
## @fn sub time_setup($year, $month, $day, $hh, $mm, $ss)
# @brief   Performs time and date setup.
# @param   $year  - year
# @param   $month - month
# @param   $day   - day
# @param   $hh    - hours
# @param   $mm    - minutes
# @param   $ss    - seconds
# @return  OK     - operations successfully comleted.
# @return  ERROR  - some error happens
sub time_setup(@)
{
   if (scalar(@_) != 6)
   {
      baselog($LOG_ERROR, "Incorrect number of parameters.");
      return $ERROR;
   }

   my ($year, $month, $day, $hh, $mm, $ss) = @_;

   my $new_date = sprintf "%02d%02d%02d%02d%4d.%02d", $month, $day, $hh, $mm, $year, $ss;

   # Set new date and time.

   unless (setupDateTime($new_date))
   {
      baselog($LOG_ERROR, "Cannot setup time and date. ($year/$month/$day (Year/Month/Day) $hh:$mm:$ss)\n", $TRUE);
      return $ERROR;
   }

   return $OK;
} ## end sub time_setup(@)

###############################################################################
## @fn sub send_arp_update($if_name, $if_ip)
# @brief   Send GARP packet to notify other network devices than this IP address has been moved to this server.
# @param   $if_name - network interface name
# @param   $if_ip - ip address
# @return  TRUE     - operations successfully comleted.
# @return  FALSE  - some error happens
sub send_arp_update(@)
{
   my ($if_name, $if_ip) = @_;

   if ((not defined $if_name) or (not defined $if_ip))
   {
      baselog($LOG_ERROR, "Incorrect number of parameters.");
      return $FALSE;
   }

   my @arp_cmd = ($ARPING, '-I', $if_name, '-A', $if_ip, '-c', '2');
   my @out;

   baselog($LOG_DEBUG, 'Sending GARP response: ' . join(' ', @arp_cmd));

   unless (do_system(\@arp_cmd, {$dsOUT => \@out}))
   {
      baselog($LOG_ERROR, 'Error executing command: ', join(' ', @out));
      return $FALSE;
   }
   return $TRUE;
} ## end sub send_arp_update(@)

###############################################################################
## @fn sub create_usb_mountpoint()
# @brief   Create usb mount point
# @param   none
# @return  $OK    - operations successfully completed.
# @return  $ERROR - some error happens
sub create_usb_mountpoint()
{
   unless (-e $tmpMountDir)
   {
      umask 0022;
      unless (do_system([$MKDIR, '-p', $tmpMountDir]))
      {
         baselog($LOG_ERROR, 'Cannot create USB mount point.', $TRUE);
         return $ERROR;
      }
   } ## end unless (-e $tmpMountDir)
   return $OK;
} ## end sub create_usb_mountpoint()

###############################################################################
## @fn sub patching_chown($spec_dir)
# @brief   Change ownership of the target directory.
# @param   $spec_dir - target directory.
# @return  $OK     - operations successfully completed.
# @return  $ERROR  - some error happens.
sub patching_chown($)
{
   my $spec_dir = shift @_;
   if (!defined $spec_dir)
   {
      baselog($LOG_ERROR, "Incorrect input parameters.");
      return $ERROR;
   }
   if ($spec_dir !~ /^$PATCHDIR/)
   {
      baselog($LOG_ERROR, "The target directory $spec_dir is not under patching directory.\n");
      return $ERROR;
   }
   if (!do_system([$CHOWN, '-R', "$NORTEL_ACCT:$GROUPS{'patchadmin'}", $spec_dir]))
   {
      baselog($LOG_ERROR, "Cannot change $spec_dir directory ownerships.\n");
      return $ERROR;
   }
   return $OK;
}  ##end sub patching_chown($)

###############################################################################
## @fn sub patching_chown($perm, $file)
# @brief   Change permissions of the target file.
# @param   $perm - new permissions.
# @param   $file - target file.
# @return  $OK     - operations successfully completed.
# @return  $ERROR  - some error happens.
sub patching_chmod($$)
{
   my ($perm, $file) = @_;
   if ((!defined $perm) or (!defined $file))
   {
      baselog($LOG_ERROR, "Incorrect input parameters.\n");
      return $ERROR;
   }
   if ($file !~ /^$PATCHDIR/)
   {
      baselog($LOG_ERROR, "The provided file $file is not under patching directory.\n");
      return $ERROR;
   }
   if (!do_system([$CHMOD, $perm, $file]))
   {
      baselog($LOG_ERROR, "Cannot change $file permissions.\n");
      return $ERROR;
   }
   return $OK;
} ## end sub patching_chmod($$)

###############################################################################
## @fn  update_hosts($fqdn_ip, $fqdn)
# @brief   This function updates /etc/hosts file with new record for FQDN.
# @param   $fqdn - host name with domain
# @param   $fqdn_ip - IP address for FQDN record in /etc/hosts file
# @return  $OK   -  file updated successfully.
# @return  $ERROR  -  some error happened.
sub update_hosts($$)
{
   my ($fqdn_ip, $fqdn) = @_;

   my $retval = $OK;

   #arrays to keep /etc/hosts file content
   my @hosts_data = ();
   my @hosts_new  = ();
   if ((!defined $fqdn_ip) or ($fqdn_ip eq ''))
   {
      baselog($LOG_ERROR, "Incorrect IP address. Check your network settings.\n", $TRUE);
      return $ERROR;
   }

   if (!do_system([$CAT, $HOSTS_TABLE_FILE], {$dsOUT => \@hosts_data}))
   {
      baselog($LOG_ERROR, "Cannot read hosts settings.\n", $TRUE);
      return $ERROR;
   }

   #should be at least configured local DNS
   my $match = $FALSE;
   foreach my $record (@hosts_data)
   {
      chomp($record);
      if ((!$match) and ($record =~ /\s+$fqdn\s*.*$/))
      {
         baselog($LOG_INFO, "Match found: '$record'. Updating with '$fqdn_ip  $fqdn'.");
         $record =~ s/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/$fqdn_ip/;
         push @hosts_new, "$record\n";
         $match = $TRUE;
      } ## end if ((!$match) and ($record...
      else
      {
         push @hosts_new, "$record\n";
      }
   } ## end foreach my $record (@hosts_data...

   # if FQDN record is not present in the /etc/hosts file
   # add new record.
   if (!$match)
   {
      baselog($LOG_INFO, "Match not found. Adding new record: '$fqdn_ip  $fqdn'.");
      push @hosts_new, "$fqdn_ip           $fqdn\n";
   }

   # save changes in the /etc/hosts file.
   if (not write_file($HOSTS_TABLE_FILE, \@hosts_new))
   {
      baselog($LOG_ERROR, "Failed to save changes to '$HOSTS_TABLE_FILE'.", $TRUE);
      $retval = $ERROR;
   }

   return $retval;
} ## end sub update_hosts($$)

## @fn replace_ntp_configs()
# @brief   This function replaces NTP configuration files during
#          installation/uninstallation of NTP SU patch
# @details During installing of new NTP rpm package some configuration
#          files can be created with '.rpmnew' filename extension. So,
#          in order to apply new configs it is necessary to replace
#          previous config files with these '.rpmnew' files (keeping
#          original config filename).
# @return $OK    (0) - no errors
# @return $ERROR (1) - error condition
sub replace_ntp_configs()
{
   my $rpmnew_configs = [];
   my $retval         = $OK;

   if (not do_system([$FIND, '/', '-regextype', 'posix-extended', '-regex', '^((/etc.*ntp)|(/var/lib/ntp)).*rpmnew$'], {$dsOUT => $rpmnew_configs}))
   {
      $retval = $ERROR;
   }
   else
   {
      foreach my $rpmnew_config (@$rpmnew_configs)
      {
         $rpmnew_config =~ /\.rpmnew$/;
         my $config = $`;
         if (defined $config)
         {
            chomp $rpmnew_config;
            if (do_system([$MV, $rpmnew_config, $config]))
            {
               baselog($LOG_INFO, "NTP configuration file '$rpmnew_config' was replaced.");
            }
            else
            {
               baselog($LOG_ERROR, "Cannot replace NTP config '$rpmnew_config'");
               $retval = $ERROR;
            }
         } ## end if (defined $config)
      } ## end foreach my $rpmnew_config (...
   } ## end else [ if (not do_system([$FIND...
   return $retval;
} ## end sub replace_ntp_configs()

