#!/usr/bin/perl

# chkconfig: 35 96 7
# config: NONE
# description: Linux Base is a set of utilities for maintenance of \
#              Nortel applications on Linux platfrom.

## @file linuxbase_srv
# @brief performs different tasks which are needed during the system booting
#        or shutting down.
# @author Alexander Kolotov
# @version 1.00 - Initial version
# @version 1.01 - route configuration is added
# @version 1.10 - add support of system parameters control
#          and $SRV_... constant are used
# @version 1.20 - Add semaphores support.
# @version 1.21 - Add restoration and print of system clock parameters
# @version 1.30 - Add installation of the Base Applications at the first bootup.
# @version 1.31 - Add sending SMMP trap during first bootup(hardening requirements)
# @version 1.35 - start/stop of the Base Applications is added
#          (base_apps_service module is used for that purpose).
# @version 1.40 - FTP setup added.
# @version 1.41 - Two colons were removed before shared functions and variables.
# @version 1.42 - check for user has been changed for group.
# @version 1.43 - Extended access points for Linux_SFTP_User and Linux_FTP_SFTP_User users
#          are mounted during service start up and unmounted during stopping
#          as well as for Linux_FTP_User users. Two functions:
#          "enable_sftp_mounts" and "disable_sftp_mounts" have been added.
# @version 1.44 - The following function have been added: print_clock_status, initialize_clock,
#          stop_ftp, stop_tftp.
# @version 1.45 - common_functions is moved on top of include list
# @version 1.46 - The following functions have been added in order to control TELNET settings
#                 stop_telnet, enable_telnet_service. Functions enable_ftp_service, enable_tftp_service
#                 are changed - semaphores stuff is moved to service_ftp_start, service_tftp_start.
# @version 1.47 - added hwRecognition stuff
# @version 1.48 - check_nortel_apps() subroutine is added. Implemented into do_start.
# @version 1.49 - disable_sftp_mounts(), enable_sftp_mounts(), prepare_sftp_jail_template() functions
#                 have been moved into the "mount_srv".
# @version 1.50 - New remove_recover() subroutine is added.
# @version 1.51 - Patch recovery added on firstboot after the base applications are installed
# @version 1.52 - Moved patch recovery to appinstall base-app install stage.
# @version 1.53 - added check for minimal hardware requirements
# @version 1.54 - Reset locked account function is added at service start up sequence.
# @version 1.55 - 'handle_hw_recognition' function has been rewritten
# @version 1.56 - now ethernet cards are checked for appropriate IPs assignment and full-duplex mode

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

use strict;
use warnings;

use common_variables;
use common_functions;
use baselog;
use RouteControl;
use base_sysctl;
use appinstall::update_sys_data;
use appinstall::appupgrade;
use appinstall::errors;
use appinstall::listgen;
use install_common;
use base_semctl;
use base_system;
use base_timedate;
use hardening::hardening_common;
use base_apps_service;
use base_ftp;
use hwRecognition;
use base_snmp;
use baseParams;

my $SRV_NAME  = 'linuxbase_srv';
my $lock_file = "/var/lock/subsys/$SRV_NAME";
my $start_msg = "Starting $SRV_NAME";
my $stop_msg  = "Stopping $SRV_NAME";

#Declarations
## @skipline
sub handle_hw_recognition();
## @skipline
sub route_management($);
## @skipline
sub alarm_management($);
## @skipline
sub sems_init();
## @skipline
sub sems_status();
## @skipline
sub remove_upgrade();
## @skipline
sub system_parameters_management($);
## @skipline
sub do_start();
## @skipline
sub do_stop();
## @skipline
sub do_status();
## @skipline
sub default_message();
## @skipline
sub start_base_app();
## @skipline
sub stop_base_app();
## @skipline
sub send_snmp_trap_on_first_bootup();
## @skipline
sub do_firstbootup_actions();
## @skipline
sub enable_ftp_service();
## @skipline
sub enable_tftp_service();
## @skipline
sub check_nortel_apps();
## @skipline
sub remove_recover();
## @skipline
sub reset_account_locks();

########################################################################
# This subroutine is a wrapper which provides management for the alarm
# utility and handles the returned value.
#  INPUT: $_[0] - action. It can be one of the following: 'remove-db',
#                                                         'clear',
#                                                         'show'
# OUTPUT: $OK or $ERROR
########################################################################
sub alarm_management($)
{
   my $action = shift @_;

   baselog($LOG_DEBUG, "Try to execute $ALARM --" . $action);

   # Hash to determine error messages
   my %err_messages = (
                       'remove-db' => "Can not remove alarms database.",
                       'clear'     => "Can not clear alarms.",
                       'show'      => "Can not get status of alarms DB."
                      );

   my $ret = $OK;

   if (defined $err_messages{$action})
   {

      # Do given action
      system("$ALARM --" . $action);
      if ($? >> 8)
      {
         baselog($LOG_ERROR, $err_messages{$action} . "\n", $TRUE);
         $ret = $ERROR;
      }
   } ## end if (defined $err_messages...
   else
   {
      baselog($LOG_ERROR, "Uknown action for the alarm utility is passed");
      $ret = $ERROR;
   }

   baselog($LOG_DEBUG, "sub alarm_management returns $ret");

   return $ret;
} ## end sub alarm_management($)

#####################################################################
# This subroutine provides interface to update and to show system
# routes
#
# INPUT  : $_[0] - action. It can be one of the following: 'update',
#                                                          'show'
# OUTPUT : $OK, $ERROR
#####################################################################
sub route_management($)
{
   my $arg   = shift @_;
   my $route = new RouteControl;
   my $ret   = $OK;

   unless (defined $route)
   {
      baselog($LOG_ERROR, "Can not create RouteControl object");
      return $ERROR;
   }
   if ($arg eq 'update')
   {
      unless ($route->apply_all('add'))
      {
         baselog($LOG_ERROR, "Can not update routes");
         $ret = $ERROR;
      }
   } ## end if ($arg eq 'update')
   elsif ($arg eq 'show')
   {
      unless ($route->show('all'))
      {
         baselog($LOG_ERROR, "Can not get routes information");
         $ret = $ERROR;
      }
   } ## end elsif ($arg eq 'show')
   undef $route;
   return $ret;
} ## end sub route_management($)

########################################################################
# This subroutine performs action to control system paramters
#  INPUT: $action - it can be one of the following: 'start',
#                                                   'stop',
#                                                   'show'
# OUTPUT: $OK or $ERROR
########################################################################
sub system_parameters_management($)
{
   my $action = shift @_;

   baselog($LOG_DEBUG, "Action $action is for sub system_parameters_management");

   my $ret = $ERROR;

   if ($action eq $SRV_START)
   {

      # Remove backup DB
      if (remove_sysctl_backup())
      {

         # Apply system parameters for Linux Base.
         if (apply_parameters('base'))
         {
            $ret = $OK;
         }
      } ## end if (remove_sysctl_backup...
   } ## end if ($action eq $SRV_START...
   elsif ($action eq $SRV_STOP)
   {
      if (remove_sysctl_backup())
      {
         $ret = $OK;
      }
   } ## end elsif ($action eq $SRV_STOP...
   elsif ($action eq $SRV_STATUS)
   {
      if (show_parameters())
      {
         $ret = $OK;
      }
   } ## end elsif ($action eq $SRV_STATUS...

   baselog($LOG_DEBUG, "sub system_parameters_management returns $ret");

   return $ret;
} ## end sub system_parameters_management($)

########################################################################
# This subroutine creates and initializes set of Linux Base semaphores.
#  INPUT: None
# OUTPUT: $OK or $ERROR
########################################################################
sub sems_init()
{
   my $ret = $ERROR;

   my $semmngr = base_semctl::new($SRV_NAME);
   if (!defined($semmngr))
   {
      my $error_descr = $!;
      baselog($LOG_ERROR, "Cannot create semaphore manager object ($error_descr).");
   }
   elsif ($semmngr->sems_create())
   {
      $ret = $OK;
   }
   return $ret;
} ## end sub sems_init()

########################################################################
# This subroutine prints table with Linux Base semaphores status.
#
#  INPUT: none
# OUTPUT: $OK or $ERROR
########################################################################
sub sems_status()
{
   my $semmngr = base_semctl::new($SRV_NAME);
   if (!defined($semmngr))
   {
      my $error_descr = $!;
      baselog($LOG_ERROR, "Cannot create semaphore manager object ($error_descr).");
      return $ERROR;
   } ## end if (!defined($semmngr)...
   $semmngr->sem_print_base_status();
   return $OK;
} ## end sub sems_status()

##############################################################################
## @fn handle_hw_recognition()
# @brief generate hwInfo file is necessary
# @param none
# @return $OK - file has been generated
# @return $ERROR - file has not been generated
# @autor Alex Arkhipov
sub handle_hw_recognition()
{
   my $hwObj = hwRecognition->new($TRUE);
   if (!defined($hwObj))
   {
      my $error_descr = $!;
      baselog($LOG_ERROR, "Cannot create hardware recognition object ($error_descr).");
      return $ERROR;
   } ## end if (!defined($hwObj))
   return ($hwObj->generate_hwinfo_file()) ? $OK : $ERROR;
} ## end sub handle_hw_recognition()

##############################################################################
## @fn check_ip_address_assignment($device;$force_restart)
# @brief Check that ip address has been assigned correctly to the given device
# @param $device - eth0 or eth1
# @param $force_restart - force restart network subsystem in case of error
# @return $OK - success
# @return $ERROR - failure
# @author Nikolay Panov
sub check_ip_address_assignment($;$)
{
   my $device        = shift @_;
   my $force_restart = shift @_;
   my %base_params   = ();
   my @output        = ();
   my $ip            = "";
   if (!$device or ($device ne 'eth0' and $device ne 'eth1'))
   {
      baselog($LOG_ERROR, "Incorrect 'device' parameter given. Only eth0/eth1 is allowed.");
      return $ERROR;
   }
   if (getParams(\%base_params))
   {
      if ($device eq 'eth0')
      {
         $ip = $base_params{'machineIP'};
      }
      else
      {
         $ip = $base_params{'machineIPTlan'};
      }

      if (do_system([$IFCONFIG, $device], {$dsOUT => \@output}))
      {
         unless (grep(/$ip/, @output))
         {
            baselog($LOG_ERROR, "IP address $ip is not assigned to $device.");
            if ($force_restart)
            {
               baselog($LOG_WARNING, "As IP address has not been properly assigned, network subsystem will be restarted.");
               if (do_system([$SERVICE, "network", "restart"]))
               {
                  if (do_system([$IFCONFIG, $device], {$dsOUT => \@output}))
                  {
                     if (grep(/$ip/, @output))
                     {
                        return $OK;  # ok, the issue has been fixed by network restart
                     }
                     else
                     {
                        baselog($LOG_ERROR, "After network restart IP address $ip still is not assigned to $device.");
                     }
                  } ## end if (do_system([$IFCONFIG...
                  else
                  {
                     baselog($LOG_ERROR, "Cannot exec ifconfig.");
                  }
               } ## end if (do_system([$SERVICE...
               else
               {
                  baselog($LOG_ERROR, "Cannot restart network subsystem.");
               }
            } ## end if ($force_restart)
            return $ERROR;
         } ## end unless (grep(/$ip/, @output...
      } ## end if (do_system([$IFCONFIG...
      else
      {
         baselog($LOG_ERROR, "Cannot exec ifconfig.");
		 return $ERROR;
      }
   } ## end if (getParams(\%base_params...
   else
   {
      baselog($LOG_ERROR, "Cannot read userinfo.txt file.");
	  return $ERROR;
   }

   return $OK;
}  ## check_ip_address_assignment()

##############################################################################
## @fn check_min_hw_requirements()
# @brief Check minimal hardware requirements
# @param none
# @return $OK - success
# @return $ERROR - failure
# @autor Alexander Khoroshilov
sub check_min_hw_requirements()
{
   my ($mem_size, $hd_size);
   my $rc = $OK;

   $mem_size = get_memory_stat();
   if (defined($mem_size))
   {
      if ($mem_size < $MIN_MEMORY_SIZE)
      {
         baselog($LOG_CRIT, "$mem_size MB does not meet the minimum memory requirement of $MIN_MEMORY_SIZE MB");
         send_snmp_trap("OSM0030", {'MEMORY_SIZE' => $mem_size, 'MIN_MEMORY_SIZE' => $MIN_MEMORY_SIZE});
         $rc = $ERROR;
      } ## end if ($mem_size < $MIN_MEMORY_SIZE...
   } ## end if (defined($mem_size)...
   else
   {
      baselog($LOG_ERROR, "get_memory_stat() returned undef value");
      $rc = $ERROR;
   }

   $hd_size = get_hd_size();
   if (defined($hd_size))
   {
      if ($hd_size < $MIN_HARD_DRIVE_SIZE)
      {
         baselog($LOG_CRIT, "$hd_size MB does not meet the minimum Hard Drive requirement of $MIN_HARD_DRIVE_SIZE MB");
         send_snmp_trap("OSM0031", {'HDD_SIZE' => $hd_size, 'MIN_HDD_SIZE' => $MIN_HARD_DRIVE_SIZE});
         $rc = $ERROR;
      } ## end if ($hd_size < $MIN_HARD_DRIVE_SIZE...
   } ## end if (defined($hd_size))
   else
   {
      baselog($LOG_ERROR, "get_hd_size() returned undef value");
      $rc = $ERROR;
   }

   # Network check section.
   #
   my $force_restart = $TRUE;
   my @output        = ();
   my $network_issue = "";
   delete_line_from_file($MOTDFILE, "Network issue detected");
   for my $device ("eth0", "eth1")
   {
      # Step 1: whether IPs are associated with eth0/eth1
      if (check_ip_address_assignment($device, $force_restart) == $ERROR)
      {
         # Second time try to restart network subsystem
         sleep 30;
         if (check_ip_address_assignment($device, $force_restart) == $ERROR)
         {
            # Third time try to restart network subsystem
            sleep 60;
            if (check_ip_address_assignment($device, $force_restart) == $ERROR)
            {
               baselog($LOG_ERROR, "After three network subsystem restart IP address is not binded yet.");
               send_snmp_trap("OSM0032", {'ETH' => $device});
               $network_issue .= "Network issue detected: cannot assign ip address to the $device interface.\n";
               $rc = $ERROR;
            } ## end if (check_ip_address_assignment...
         } ## end if (check_ip_address_assignment...
      } ## end if (check_ip_address_assignment...

      # Step 2: whether NICs are in full duplex mode
      if (do_system([$ETHTOOL, $device], {$dsOUT => \@output}))
      {
         unless (grep(/Duplex: Full/, @output))
         {
            baselog($LOG_ERROR, "Ethernet card $device is not in full-duplex mode.");
            send_snmp_trap("OSM0033", {'ETH' => $device});
            $network_issue .= "Network issue detected: $device is not in full-duplex mode.\n";
         } ## end unless (grep(/Duplex: Full/...
      } ## end if (do_system([$ETHTOOL...
      else
      {
         baselog($LOG_ERROR, "Cannot exec $ETHTOOL command.");
         $rc = $ERROR;
      }
   } ## end for my $device ("eth0",...
   if ($network_issue)
   {
      # Add new text banner into motd file
      # Open motd file to append
      my $fd;
      if (not open($fd, '>>', $MOTDFILE))
      {
         baselog($LOG_ERROR, "Can't open file: '$MOTDFILE'");
      }
      else
      {
         # Write to motd file
         print $fd "$network_issue\n";

         # Close motd file
         if (not close $fd)
         {
            baselog($LOG_ERROR, "Cannot close the file descriptor: $!.");
         }
      } ## end else [ if (not open($fd, '>>'...
   } ## end if ($network_issue)

   return $rc;
} ## end sub check_min_hw_requirements()

##############################################################################
## @fn do_start()
# @brief Performs actions during booting the system
# @param none
# @return $OK - success
# @return $ERROR - any failure occured
sub do_start()
{
   my $ret = $OK;

   # Each special handler has to be implemented by a separate subroutine.

   # Re-set locked accounts
   $ret |= reset_account_locks();

   #Check Nortel Apllications installation status
   $ret |= check_nortel_apps();

   # Initialize semaphore set
   $ret |= sems_init();

   # Perform the very first bootup actions
   $ret |= do_firstbootup_actions();

   # Remove alarms DB
   $ret |= alarm_management("remove-db");

   # Remove default upgrade archive
   $ret |= remove_upgrade();

   # Remove recovery data
   $ret |= remove_recover();

   # Update route configuration
   $ret |= route_management("update");

   # Update files of system data
   $LASTERR = 'NULL';
   if (!appinstall::update_sys_data::update_sdb())
   {
      if ($LASTERR ne 'NULL')
      {
         baselog($LOG_ERROR, "$appinstall::errors::ERRORDB{$LASTERR}");
      }
      $ret = $ERROR;
   } ## end if (!appinstall::update_sys_data::update_sdb...

   # Apply new system parameters
   $ret |= system_parameters_management($SRV_START);

   # Initialize system clock's parameters
   $ret |= initialize_clock();

   # firewall setup must be done before base apps start to have
   # only one firewall restart operation.
   # Remove base service firewall rules
   if ((-e $FIREWALL_RULES_FILE) and (!unlink($FIREWALL_RULES_FILE)))
   {
      baselog($LOG_ERROR, 'Cannot reset base firewall rules.');
      $ret = $ERROR;
   }

   # Reset FTP/TFTP/TELNET setup
   $ret |= enable_ftp_service();
   $ret |= enable_tftp_service();

   $ret |= enable_telnet_service();

   $ret |= start_base_app();

   # Perform hw recognition actions
   # Need to be below starting base applications
   # as cppmUtil is doing some stuff for us
   $ret |= handle_hw_recognition();

   # Check minimal hardware requirements
   $ret |= check_min_hw_requirements();

   print $start_msg;
   if ($ret == $OK)
   {
      system($TOUCH, $lock_file);
      status_success($start_msg);
   }
   else
   {
      status_failure($start_msg);
   }
   return $ret;
} ## end sub do_start()

########################################################################
# This subroutine performs actions during shutting the system down
#  INPUT: None
# OUTPUT: $OK or $ERROR
########################################################################
sub do_stop()
{
   my $ret = $OK;

   # Each special handler has to be implemented by a separate subroutine.

   # Stop FTP/TFTP service
   $ret = stop_ftp();
   $ret |= stop_tftp();

   # Stop TELNET service
   $ret |= stop_telnet();

   # Stop Base Applications
   $ret |= stop_base_app();

   # Clear system-wide alarms
   $ret |= alarm_management("clear");

   # Remove backup-file for system parameters
   $ret |= system_parameters_management($SRV_STOP);

   unlink($lock_file);

   print $stop_msg;
   if ($ret == $OK)
   {
      status_success($stop_msg);
   }
   else
   {
      status_failure($stop_msg);
   }

   return $ret;
} ## end sub do_stop()

########################################################################
# This subroutine performs gets the information about controlled objects
#  INPUT: None
# OUTPUT: $OK or $ERROR
########################################################################
sub do_status()
{
   my $ret = $OK;

   # Each special handler has to be implemented by a separate subroutine.

   # Get status of alarms DB
   $ret = alarm_management("show");

   # Get status of the changed system parameters
   $ret |= system_parameters_management($SRV_STATUS);

   # Get status of configured routes
   $ret |= route_management("show");

   # Get status of semaphores DB
   $ret |= sems_status();

   # Get status of system clock
   $ret |= print_clock_status();

   return $ret;
} ## end sub do_status()

###############################################################################
## @fn reset_account_locks()
# @brief It resets faillog counter(unlocks all accounts)
# @return  $OK -  operation succeed.
# @return  $ERROR - error occurred
sub reset_account_locks()
{
   my $cmdret;
   baselog($LOG_INFO, 'Resetting locked accounts.');
   if (not do_system([$FAILLOG, '-r'], {$dsRETVAL => \$cmdret}))
   {
      baselog($LOG_ERROR, "Cannot reset locked accounts (return: $cmdret).");
      return $ERROR;
   }
   return $OK;
} ## end sub reset_account_locks()

###############################################################################
## @fn remove_upgrade()
# @brief This subroutine checks default upgrade backup archive and
# removes it if the one exists.
# @return  $OK -  operation succeed.
# @return  $ERROR - error occurred
sub remove_upgrade()
{
   if (-e $UPGRADE_BACKUP)
   {
      if (not do_system([$RM, '-rf', $UPGRADE_BACKUP]))
      {
         baselog($LOG_ERROR, 'Default upgrade archive found but cannot be deleted.');
         return $ERROR;
      }
      baselog($LOG_INFO, "Default upgrade archive ($UPGRADE_BACKUP) deleted.");
   } ## end if (-e $UPGRADE_BACKUP...
   return $OK;
} ## end sub remove_upgrade()

###############################################################################
## @fn remove_recover()
# @brief This function cleans temporary recovery directory.
# @return  $OK -  operation succeed.
# @return  $ERROR - error occurred
sub remove_recover()
{
   if (-d $TEMP_RESTORE_DIR)
   {

      my @rmlist = ();
      if (!do_system([$LS, $TEMP_RESTORE_DIR], {$dsOUT => \@rmlist}))
      {
         baselog($LOG_ERROR, 'Cannot check restore temporary directory.');
         return $ERROR;
      }

      chomp(@rmlist);
      baselog($LOG_DEBUG, "'$TEMP_RESTORE_DIR' content: @rmlist.");

      if ((scalar(@rmlist)) and (not do_system([$RM, '-rf', @rmlist], {$dsCHDIR => $TEMP_RESTORE_DIR})))
      {
         baselog($LOG_ERROR, 'Cannot clean up restore temporary directory.');
         return $ERROR;
      }
   } ## end if (-d $TEMP_RESTORE_DIR...
   return $OK;
} ## end sub remove_recover()

###############################################################################
## @fn start_base_app()
# @brief This function starts Base Applications
# @details
# @param None
# @return
#   - $OK    - Applications started successfully
#   - $ERROR - some errors happened.
# @author Evgeny Lazarev
# @date May 2008
# @note
sub start_base_app()
{
   my $retval = $OK;
   my $app = new base_apps_service({$APPL_TYPE => $TYPE_BASE_APPL});
   if (!defined($app))
   {
      $retval = $ERROR;
      baselog($LOG_ERROR, "Can not create base_apps_service object.");
   }
   else
   {
      if (!$app->base_app_start())
      {
         $retval = $ERROR;
      }
   } ## end else [ if (!defined($app))
   return $retval;
} ## end sub start_base_app()

##############################################################################
## @fn stop_base_app()
# @brief This function stops Base Applications
# @param None
# @return
#   - $OK    - Applications stopped successfully
#   - $ERROR - some errors happened.
# @author Evgeny Lazarev
# @date May 2008
sub stop_base_app()
{
   my $retval = $OK;
   my $app = new base_apps_service({$APPL_TYPE => $TYPE_BASE_APPL});
   if (!defined($app))
   {
      $retval = $ERROR;
      baselog($LOG_ERROR, "Can not create base_apps_service object.");
   }
   else
   {
      if (!$app->base_app_stop())
      {
         $retval = $ERROR;
      }
   } ## end else [ if (!defined($app))
   return $retval;
} ## end sub stop_base_app()

##############################################################################
##@ fn send_snmp_trap_on_first_bootup
# @brief Sends SNMP traps
# @details This subroutine is intended to send SNMP traps on the very first
#          Linux Base start up in order to reflect the state of the system after
#          installation (e.g. send SNMP traps in accordance to the current
#          Hardening policies). It is due to the SNMP application (as a Base
#          Application) is installed during the very first boot up and it is
#          necessary send SNMP traps after this moment only.
# @return OK - SNMP traps are sent sucessfully
# @return ERROR - some error happens
sub send_snmp_trap_on_first_bootup()
{
   if (do_enhanced_hardening_action($H_IF_SEND_SNMP))
   {
      return $OK;
   }

   #No error message is needed it should be provided by do_enhanced_hardening_action.
   return $ERROR;
} ## end sub send_snmp_trap_on_first_bootup()

##############################################################################
## @fn do_firstbootup_actions
# @brief Performs the very forst bootup actions
# @details The subroutine checks for existence $BASEFIRSTBOOTUP lock file which
#          is created on Linux Base installation stage. If it is exist, the
#          subroutine performs the very first bootup actions.
#
#          After all the actions performing the lock file is removed.
# @return OK - All actions are performed sucessfully
# @return ERROR - some error happens
# @todo TODO: It makes sense to move this functionality in the separate module
#             and use the Plug-in Manager - it will allow adding of new first
#             startup actions very easyly.
sub do_firstbootup_actions()
{
   my $retval = $OK;

   if (-e $BASEFIRSTBOOTUP)
   {
      if (!base_app_install())
      {
         $retval = $ERROR;
      }

      # Send an SNMP alarm to indicate first boot-up completion
      $retval |= send_snmp_trap_on_first_bootup();

      if ((unlink $BASEFIRSTBOOTUP) != 1)
      {
         baselog($LOG_ERROR, "Cannot remove firstboot lock file.");
         $retval |= $ERROR;
      }
   } ## end if (-e $BASEFIRSTBOOTUP...
   return $retval;
} ## end sub do_firstbootup_actions()

###############################################################################
## @fn enable_ftp_service()
# @brief Starts FTP service and changes firewall rules.
# @return OK - the service is running sucessfully
# @return ERROR - some error happens
sub enable_ftp_service()
{

   #Try to start the service
   if (is_option_permitted($FTP))
   {
      if (not service_ftp_start())
      {
         baselog($LOG_INFO, 'Cannot start FTP service.');
         return $ERROR;
      }
   } ## end if (is_option_permitted...
   return $OK;
} ## end sub enable_ftp_service()

###############################################################################
## @fn enable_tftp_service()
# @brief Starts TFTP service and changes firewall rules.
# @return OK - the service is running sucessfully
# @return ERROR - some error happens
sub enable_tftp_service()
{

   #Try to start the service
   if (is_option_permitted($TFTP))
   {
      if (not service_tftp_start())
      {
         baselog($LOG_INFO, 'Cannot start TFTP service.');
         return $ERROR;
      }
   } ## end if (is_option_permitted...
   return $OK;
} ## end sub enable_tftp_service()

###############################################################################
## @fn enable_telnet_service()
# @brief Starts TELNET service and changes firewall rules.
# @return OK - the service is running sucessfully
# @return ERROR - some error happens
sub enable_telnet_service()
{

   #Try to start the service
   if (is_option_permitted($TELNET))
   {
      if (not service_telnet_start())
      {
         baselog($LOG_ERROR, 'Cannot start TELNET service.');
         return $ERROR;
      }
   } ## end if (is_option_permitted...
   return $OK;
} ## end sub enable_telnet_service()

###############################################################################
## @fn initialize_clock()
# @brief Initialize clock
# @return OK - operation successful
# @return ERROR - some error happened
sub initialize_clock()
{
   my $retval = $OK;
   if (!clock_parameters_restore())
   {
      baselog($LOG_ERROR, "Can not initialize clock.");
      $retval = $ERROR;
   }
   return $retval;
} ## end sub initialize_clock()

###############################################################################
## @fn print_clock_status()
# @brief prints clock parameters.
# @return OK - operation successful
# @return ERROR - some error happened
sub print_clock_status()
{
   my $retval = $OK;
   if (!print_clock_params())
   {
      baselog($LOG_ERROR, "Can not print clock parameters.");
      $retval = $ERROR;
   }
   return $retval;
} ## end sub print_clock_status()

###############################################################################
## @fn stop_ftp()
# @brief disable ftp service
# @return OK - operation successful
# @return ERROR - some error happened
sub stop_ftp()
{
   my $retval = $OK;
   if (!service_ftp_stop())
   {
      baselog($LOG_ERROR, "Can not stop ftp service.");
      $retval = $ERROR;
   }
   return $retval;
} ## end sub stop_ftp()

###############################################################################
## @fn stop_tftp()
# @brief disable tftp service
# @return OK - operation successful
# @return ERROR - some error happened
sub stop_tftp()
{
   my $retval = $OK;
   if (!service_tftp_stop())
   {
      baselog($LOG_ERROR, "Can not stop tftp service.");
      $retval = $ERROR;
   }
   return $retval;
} ## end sub stop_tftp()

###############################################################################
## @fn stop_telnet()
# @brief disable telnet service
# @return OK - operation successful
# @return ERROR - some error happened
sub stop_telnet()
{
   my $retval = $OK;
   if (!service_telnet_stop())
   {
      baselog($LOG_ERROR, "Can not stop TELNET service.");
      $retval = $ERROR;
   }
   return $retval;
} ## end sub stop_telnet()

###############################################################################
## @fn check_nortel_apps()
# @brief check installation status of nortel applications
# @return OK - operation successful
# @return ERROR - some error happened
sub check_nortel_apps()
{
   baselog($LOG_DEBUG, "To start checking nortel applications.");
   unless (-e $CONFVER)
   {
      baselog($LOG_INFO, "Nortel applications are not installed.", $TRUE);
      return $OK;
   }
   my $params = use_confver($CONFVER);
   my $status = $params->{'STATUS'};
   unless (defined $status)
   {
      baselog($LOG_INFO, "Old version of appinstall was used. $CONFVER file do not contain STATUS field.");
      return $OK;
   }
   if ($status eq $CONFVER_STATES{'COMPLETE'})
   {

      #applications are successfully installed.
      baselog($LOG_DEBUG, "applications are installed successfully.");
      return $OK;
   } ## end if ($status eq $CONFVER_STATES...
   elsif (($status eq $CONFVER_STATES{'STARTED'}) or ($status eq $CONFVER_STATES{'UNINSTALLING'}))
   {

      #rpm files are not installed completely or not removed completely
      baselog($LOG_INFO, "Check RPM database.");
      if (is_rpm_database_corrupted())
      {
         $LASTERR = 'RPMBD';
         baselog($LOG_ERROR, "RPM database is CORRUPTED! System must be reinstalled!", $TRUE);
         return $ERROR;
      } ## end if (is_rpm_database_corrupted...
      baselog($LOG_INFO, "RPM database is valid.");
      baselog($LOG_INFO, "Try to remove particularly installed applications.", $TRUE);
   } ## end elsif (($status eq $CONFVER_STATES...
   elsif ($status eq $CONFVER_STATES{'RPM_INSTALLED'})
   {

      #rpm files are correctly installed but post-install section is not
      #performed as well.
      baselog($LOG_INFO, "RPM files of Nortel applications was installed, but post-install section is failed.", $TRUE);
      baselog($LOG_INFO, "Applications will be removed.", $TRUE);
   } ## end elsif ($status eq $CONFVER_STATES...
   else
   {

      #unsupported STATUS field in CONFVER.
      baselog($LOG_WARNING, "The '$CONFVER' file was modify by someone. Check the state of Nortel applications.");
      return $ERROR;
   } ## end else [ if ($status eq $CONFVER_STATES...

   #remove installed rpms
   # if patches were applyed for nortel applications this subroutine will not remove them.
   # if patches were applyed and power failure was occured in step then patches are roll back,
   # this subroutine will not remove nortel applications and return error. If patches were rolled back than
   # all correct.
   $INSTVER = $ARCHVER;
   my $app_rpms = get_app_rpms($params->{'APP_INSTALLED'});
   unless (defined $app_rpms)
   {
      baselog($LOG_ERROR, "Cannot get list of applications rpm files.");
      return $ERROR;
   }
   unless (uninstall_rpms(@{$app_rpms}))
   {
      baselog($LOG_ERROR, "Cannot remove applications RPMs", $TRUE);
      return $ERROR;
   }
   appinstall::appupgrade::application_cleanup();
   baselog($LOG_INFO, "Nortel applications were removed.", $TRUE);
   return $OK;
} ## end sub check_nortel_apps()

########################################################################
# This subroutine prints usage help
#  INPUT: None
# OUTPUT: None
########################################################################
sub default_message()
{
   print "Usage: $SRV_NAME {$SRV_START|$SRV_STOP|$SRV_STATUS}\n";
}

if (warning_if_not_root_uid())
{
   exit($ERROR);
}

our $retval = $OK;

if (!defined @ARGV)
{

   default_message();
   exit $OK;
} ## end if (!defined @ARGV)

baselog($LOG_DEBUG, join(" ", @ARGV));

baselog($LOG_INFO, "$SRV_NAME started");

if ($ARGV[0] eq $SRV_START)
{
   $retval = do_start();
}
elsif ($ARGV[0] eq $SRV_STOP)
{
   $retval = do_stop();
}
elsif ($ARGV[0] eq $SRV_STATUS)
{
   $retval = do_status();
}
else
{
   default_message();
   $retval = $ERROR;
}

baselog($LOG_INFO, "$SRV_NAME finished");

exit $retval;
