#!/usr/bin/perl
# The following three lines are required for chkconfig tool
# chkconfig: 35 97 6
# description: application startup script
# config: /var/opt/nortel/base/appconfig/init.xml
#
##############################################################
## @file appstartup
# @brief    application manipulation script.
# @details  This script is used to manage the application
#           startup (start, stop, restart, status)
# @autor    Ilya Teterev, Peter Kascheev
# @version  1.00 - Initial version
# @version  1.10 - support of kernel parameter changing. New action
#                  'reload' is supported. Support of $SRV_...
#                  constant is added.
# @version  1.20 - Semaphores is introduced to protect from
#                  simultaneously running copies.
# @version  1.30 - base_apps_service using is added
# @version  1.31 - POD section was added; the usage is displayed by the
#                  common function - print_pod_usage() now.
# @version  1.40 - Base Applications support added. Base applications
#                  and Nortel applications are started separately.
# @version  1.41 - Two colons were removed before shared functions
#                  and variables.
# @version  1.42 - Check for unexpected parameter after
#                  start/stop(etc) commands is added.
# @version  1.50 - Check for already starting by monit is added
# @version  1.60 - Modified to support application list as parameter
# @version  1.61 - Modified main function to use is_cppm() function to define is CP-PM or not.
# @version  1.62 - Modified main function to use recover_env_path to include /bin and /usr/bin
#                  in the $ENV{'PATH'}
# @version  1.63 - Check for running by appstartwait is added
##############################################################

=pod

=head1 NAME

B<appstart> - tool to control applications.

=head1 SYNOPSIS

B<appstart> [B<< <app_name_list command> >>] B<start>|B<stop>|B<restart>|B<reload>|B<status>|B<--help>

=head1 DESCRIPTION

The B<appstart> command allows operation to control application life cycle:
start, stop, get status of all applications together or for a particular
application.  If I<app_name> parameter is provided then the I<command> 
is applied to this particular application. If there is no I<app_name>
provided then the I<command> is applied to  all installed applications.
There is one special application name - I<monit>. It is dedicated to control
I<monit> (see example section).

=head1 OPTIONS

=over 4

=item B<start> 

Start application(s)

=item B<stop> 

Stop application(s)

=item B<restart> 

Restart application(s) - this is equivalent to start and then stop sequence.

=item B<status> 

Get status of application(s)

=item B<reload> 

Stops applications, reparse system settings data and start all applications.

=item B<--help>

Print this help message and exit.

=back

=head1 EXAMPLES

=over 4

=item B<appstart> I<start>

Start all applications

=item B<appstart> I<sps stop>

Stop I<sps> application only

=item B<appstart> I<status>

Get status of all applications

=item B<appstart> I<reload>

Reload system data and restart applications

=item B<appstart> I<< gk <parameter> >>

Run I<gk> startup script with I<< <parameter> >> parameter.

=item B<appstart> I<< gk tps <parameter> >>

Run I<gk> and I<tps> startup script with I<< <parameter> >> parameter.
Parameter can be <start>, <stop>, <restart>, <status>

=item B<appstart> I<< monit <parameters> >>

Run I<monit> startup program with I<< <parameters> >> parameters.

=back

=head1 CAVEATS

The B<appstart> command requires B<root> password to be run.
There is no control whether applications are running or not. So, if
applications are already running and operator invokes B<appstart> I<start> then
all applications will be started once again (depending on the behaviour
of the respective application startup script).

=cut

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

use warnings;
use strict;

use Switch;
use Data::Dumper;

use common_variables;
use common_functions;
use install_common;
use baselog;
use base_apps_service;
use base_semctl;
use hwRecognition;
use CommonInstallUtils;
use base_monit;
use base_led;

my $APPSTART_SUBSYSTEM = 'APPSTART';
my $MONIT_SUBSYSTEM    = 'MONIT';

my $APPSTARTWAIT_NAME = 'appstartwait';
my $APPSTARTWAIT      = '/opt/nortel/base/appinstall/bin/' . $APPSTARTWAIT_NAME;

sub main();

exit(main());

sub is_run_by_appstartwait();

sub main()
{

   if (!scalar(@ARGV))
   {
      print_pod_usage();
      return $ERROR;
   }
   elsif (    (($ARGV[0] eq $SRV_STOP) or ($ARGV[0] eq $SRV_START) or ($ARGV[0] eq $SRV_RESTART) or ($ARGV[0] eq $SRV_STATUS) or ($ARGV[0] eq $SRV_RELOAD))
          and (scalar(@ARGV) > 1))
   {
      baselog($LOG_ERROR, "Incorrect parameter '$ARGV[1]'.", $TRUE);
      print_pod_usage();
      return $ERROR;
   } ## end elsif ((($ARGV[0] eq $SRV_STOP...

   if ($ARGV[0] =~ /help$/)
   {
      print_pod_usage();
      return $OK;
   }

   baselog($LOG_DEBUG, "appstart is invoked with parameters :" . Dumper(\@ARGV));
   recover_env_path();

   if ($ARGV[0] eq 'monit')
   {
      my @parm = @ARGV;
      if (!defined($ARGV[1]))
      {
         print "Not enough parameters.\n";
      }
      else
      {
         shift @parm;
         do_monit([@parm]);
      }

      # No need to continue
      return $OK;
   } ## end if ($ARGV[0] eq 'monit'...

   signals_ignore();

   my $flag = $NOWAIT_FLAG;
   my $timeout;
   my $sem_subsystem = $APPSTART_SUBSYSTEM;

   if (is_run_by_monit())
   {

      # Check for already running scripts
      if ((scalar(@ARGV) > 1) and ($ARGV[0] ne $BASE_APPS))
      {
         if (is_monit_already_trying($ARGV[0]))
         {

            # Just return OK because monit is already
            # trying to run application
            return $OK;
         } ## end if (is_monit_already_trying...
      } ## end if ((scalar(@ARGV) > 1...

      # Set necessary parameters
      $flag          = $WAIT_FLAG;
      $timeout       = $MONITSTARTUP_SEM_WAIT_TIME;
      $sem_subsystem = $MONIT_SUBSYSTEM;
   } ## end if (is_run_by_monit())

   elsif (is_run_by_appstartwait())
   {

      # Set necessary parameters
      $flag    = $WAIT_FLAG;
      $timeout = $APPSTARTWAIT_SEM_WAIT_TIME;

      if (defined($ENV{"APPSTARTWAIT"}))
      {
         $timeout = $ENV{"APPSTARTWAIT"};
         baselog($LOG_INFO, "The environment variable APPSTARTWAIT defined. The timeout is set to $timeout");
      }

      $sem_subsystem = $APPSTART_SUBSYSTEM;
   } ## end elsif (is_run_by_appstartwait...

   my $semmngr = base_semctl::new($sem_subsystem);
   if (!defined($semmngr))
   {
      baselog($LOG_ERROR, "Cannot create semaphore manager object ($!).");
      return $ERROR;
   }

   if (!$semmngr->sem_take($SEM_APPSTART, $flag, $timeout))
   {
      baselog($LOG_WARNING, "Appstart operation aborted.\n", $TRUE);
      undef $semmngr;
      return $ERROR;
   } ## end if (!$semmngr->sem_take...
   baselog($LOG_INFO, 'Appstartup started');

   my $retval = $OK;
   my $app;

   if ($ARGV[0] eq $BASE_APPS)
   {
      $app = new base_apps_service({$APPL_TYPE => $TYPE_BASE_APPL});
      shift(@ARGV);
   }
   else
   {
      if (scalar(@ARGV) == 1)
      {

         # if management of the Nortel applications is required
         $app = new base_apps_service({$APPL_TYPE => $TYPE_NORTEL_APPL});
      } ## end if (scalar(@ARGV) == 1...
      else
      {

         # if management of the particular application is required
         $app = new base_apps_service({$APPL_TYPE => $TYPE_ALL_APPL});
      } ## end else [ if (scalar(@ARGV) == 1...
   } ## end else [ if ($ARGV[0] eq $BASE_APPS...

   if (defined $app)
   {
      switch ($ARGV[0])
      {
         case "$SRV_STOP"
         {
            unless ($app->stop())
            {
               baselog($LOG_ERROR, "Applications can not be stopped\n", $TRUE);
               $retval = $ERROR;
            }
         } ## end case "$SRV_STOP"
         case "$SRV_START"
         {
            unless ($app->start())
            {
               baselog($LOG_ERROR, "Applications can not be started\n", $TRUE);
               $retval = $ERROR;
            }
         } ## end case "$SRV_START"
         case "$SRV_STATUS"
         {
            unless ($app->status())
            {
               baselog($LOG_ERROR, "Applications status is unavailable\n", $TRUE);
               $retval = $ERROR;
            }
         } ## end case "$SRV_STATUS"
         case "$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 case "$SRV_RESTART"
         case "$SRV_RELOAD"
         {
            unless ($app->reload())
            {
               baselog($LOG_ERROR, "Applications reload failed\n" . $TRUE);
               $retval = $ERROR;
            }
         } ## end case "$SRV_RELOAD"
         else
         {
            my @parm = @ARGV;
            unless ($app->app_management(\@parm))
            {
               baselog($LOG_ERROR, "Application manage failed\n", $TRUE);
               $retval = $ERROR;
            }
         } ## end else
      } ## end switch
      undef $app;
   } ## end if (defined $app)
   else
   {
      baselog($LOG_ERROR, "Can not create base_apps_service object");
      $retval = $ERROR;
   }

   ## if CP-PM platform type, turn status LED green on startup
   if (is_cppm())
   {
      if (($ARGV[0] ne $BASE_APPS))
      {  # we're looking for application startup, not base
         if (($ARGV[0] eq $SRV_START) or (defined($ARGV[1]) && ($ARGV[1] eq $SRV_START)))
         {  # only on start
            turn_led_green();
         } ## end if (($ARGV[0] eq $SRV_START...
      } ## end if (($ARGV[0] ne $BASE_APPS...
   } ## end if (is_cppm())
   
   baselog($LOG_INFO, "Appstartup finished");
   if (!$semmngr->sem_give($SEM_APPSTART))
   {
      baselog($LOG_WARNING, "Cannot release appstart semaphore.");
   }
   undef $semmngr;

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

## @fn sub is_run_by_appstartwait()
# @brief checks that appstartup is triggered by appstartwait link
# @param none
# @return $TRUE  - if current program is run by appstartwait
# @return $FALSE - if current program is not run by appstartwait
# @author Alexander Dudnik
# @date January 2009
sub is_run_by_appstartwait()
{
   return (($0 eq $APPSTARTWAIT) ? $TRUE : $FALSE);
}
