#!/usr/bin/perl
## @file sysbackup_task
# @details This script is pre-backup step. It parses configuration
#          files and collects all data to the target backup directory.
#          It is executed only by cron daemon to perform backup.
#
# @param $ARGV[0] - path to configuration file
#                   for fsbackup
# @param $ARGV[1] - specific key (optional)
#                   supported keys:
#                   "--upgrade" - to keep default upgrade backup archive
#                                 under /admin directory
# @return $OK    - OK
# @return $ERROR - ERROR
#
# @date October 2006
# @author Kate Bereznyakova
# @version 1.12 - Change sequence of baselog and common_functions
# @version 1.11 - Two colons were removed before shared functions and variables.
# @version 1.10 - Backup actions are moved to function "do_backup"
#          in "backup.pm".
# @version 1.00 - Initial version

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

use warnings;
use strict;
use common_variables;
use common_functions;
use baselog;
use Data::Dumper;
use recovery::backup;
use base_semctl;

## @skipline
sub main();  #entry point

## @skipline
sub cleanup();  #Handler for "Ctrl+C"

exit(main());

$SIG{INT} = \&cleanup;
###########################################################
#               Main function (entry point)               #
###########################################################
sub main()
{
   if (!is_right_user($NORTEL_ACCT))
   {
      print "You are not authorised to run '" . get_basename($0) . "' command.\n";
      return $ERROR;
   }

   my $config     = $ARGV[0];
   my $retval     = $ERROR;
   my $is_upgrade = $FALSE;
   my @semlist    = ($SEM_BACKUP, $SEM_PATCH);

   if (!-f $config)
   {
      baselog($LOG_ERROR, "Usage: sysbackup_task <path to configuration file>");
      return $ERROR;
   }

   # create semaphore manager object
   my $semmngr = base_semctl::new("SYSBACKUP");
   if (!defined($semmngr))
   {
      baselog($LOG_ERROR, "Cannot create semaphore manager object ($!).");
      return $ERROR;
   }
   if (!$semmngr->sem_take(\@semlist, IPC_NOWAIT))
   {
      undef $semmngr;
      return $ERROR;
   }

   my $arg1 = "";

   if ((defined($ARGV[1])) && ($ARGV[1] eq "--upgrade"))
   {
      $arg1 = "--upgrade";
   }

   # do backup operation
   if (do_backup($config, $arg1))
   {
      $retval = $OK;
   }
   else
   {
      $retval = $ERROR;
   }

   if (!$semmngr->sem_give(\@semlist))
   {
      baselog($LOG_WARNING, "Cannot release $SEM_BACKUP and $SEM_PATCH semaphores.");
   }

   # destroy the object
   undef $semmngr;

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

#------------------------------------------------
#  Handler for "Ctrl+C"
##------------------------------------------------
sub cleanup()
{
   return;
}
