#!/usr/bin/perl
## @file appBackup
# @brief It backup applications to the target LinuxBase server.
# @details  Successful operation returns 0, otherwise 1 will be returned.
# @param hostname - target hostname to backup (key parameter to find the data
#                    related to the deployment operation).
# @param IP - ip-address of the target host
# @param mode - backup method ('DM' - Deployment Manager, 'BS' - Backup Server)
# @param host - backup server IP
# @param path - path where backup archive will be created
# @param user - backup user ID
# @param pwd  - not encrypted backup user password
# @author Kate Bazhanova
# @date June 2008
# @version 1.00 - Initial version
# @version 1.01 - Two colons were removed before shared functions and variables.
# @version 1.10 - Backup operation status update is changed.
# @version 1.11 - Modified update_section function call to keep all error messages
# @version 1.12 - Modified appBackup function to synchronize deployment.xml file with target
# @version 1.13 - Updated log records with hostname and IP information.
# @version 1.14 - "/error" and "errorMsg" replaced with variables.
#                 some update_deploy_error() calls were updated to keep error code
#                 from previous step.
# @note none

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

use strict;
use warnings;
use baselog;
use base_deploy;
use common_variables;
use Getopt::Long;
use CommonInstallUtils;

## @skipline
sub appBackup();
exit(appBackup());

###############################################################################
## @fn appBackup()
# @brief   Main function. It checks input parameters and implements general
#          logic.
# @details None.
# @param   $hostname - target hostname to deploy
# @param   $ip - ip-address of the target host
# @param   $mode - restore method ('DM' - Deployment Manager, 'BS' - Backup Server)
# @param   $host - backup server IP
# @param   $path - path to absolute restore achive file name on the backup server
# @param   $user - backup user ID
# @param   $pwd  - not encrypted password
# @return  $OK (0)    -  deployment succeed
# @return  $ERROR (1) -  deployment failed
# @author  Kate Bazhanova
# @date    June 2008

sub appBackup()
{
   my $hostname = undef;
   my $ip       = undef;
   my $mode     = undef;
   my $host     = undef;
   my $path     = undef;
   my $file     = undef;
   my $user     = undef;
   my $pwd      = undef;
   my $restored = $TRUE;

   GetOptions(
              "hostname:s" => \$hostname,
              "IP:s"       => \$ip,
              "mode:s"     => \$mode,
              "host:s"     => \$host,
              "path:s"     => \$path,
              "user:s"     => \$user,
              "pwd:s"      => \$pwd
             );

   my $retval = $OK;

   # check input parameters section.
   if ((!defined $hostname) or ($hostname eq ''))
   {
      baselog($LOG_ERROR, 'Hostname is undefined.');
      return $ERROR;
   }

   my $cfg_file = get_deploy_cfg_path($hostname);

   if ((!defined $ip) or ($ip eq ''))
   {
      baselog($LOG_ERROR, 'TLAN is undefined.');
      update_section($cfg_file, $DEPERRORPATH, 'UNPA');
      reset_status($cfg_file);
      return $ERROR;
   } ## end if ((!defined $ip) or ...

   baselog($LOG_INFO, "$hostname, $ip. Starting backup operation.");

   if (!validateIP($ip))
   {
      baselog($LOG_ERROR, "Invalid TLAN IP data: $ip.");
      update_section($cfg_file, $DEPERRORPATH, 'INVIP');
      reset_status($cfg_file);
      return $ERROR;
   } ## end if (!validateIP($ip))

   if ((!defined $mode) or !(($mode eq $DEPLOYMODE{DM}) or ($mode eq $DEPLOYMODE{BS})))
   {
      baselog($LOG_ERROR, 'Backup method is undefined');
      update_section($cfg_file, $DEPERRORPATH, 'UNMTHD');
      reset_status($cfg_file);
      return $ERROR;
   } ## end if ((!defined $mode) or...

   if ((!defined $path) or ($path eq ''))
   {
      baselog($LOG_ERROR, 'Path to backup archive is undefined.');
      update_section($cfg_file, $DEPERRORPATH, 'UNPTH');
      reset_status($cfg_file);
      return $ERROR;
   } ## end if ((!defined $path) or...

   if ($mode eq $DEPLOYMODE{BS})
   {
      if ((!defined $host) or ($host eq ''))
      {
         baselog($LOG_ERROR, 'Backup server IP is undefined.');
         update_section($cfg_file, $DEPERRORPATH, 'BKUPIPN');
         reset_status($cfg_file);
         return $ERROR;
      } ## end if ((!defined $host) or...

      if (!validateIP($host))
      {
         baselog($LOG_ERROR, "Invalid Backup server IP data: $host.");
         update_section($cfg_file, $DEPERRORPATH, 'INVIP');
         reset_status($cfg_file);
         return $ERROR;
      } ## end if (!validateIP($host)...

      if ((!defined $user) or ($user eq ''))
      {
         baselog($LOG_ERROR, 'Backup user ID is undefined.');
         update_section($cfg_file, $DEPERRORPATH, 'UNUSR');
         reset_status($cfg_file);
         return $ERROR;
      } ## end if ((!defined $user) or...

      if (!defined $pwd)
      {
         baselog($LOG_ERROR, 'Backup user password is undefined.');
         update_section($cfg_file, $DEPERRORPATH, 'UNPWD');
         reset_status($cfg_file);
         return $ERROR;
      } ## end if (!defined $pwd)
   } ## end if ($mode eq $DEPLOYMODE...

   # end: check input parameters section.

   my $deployMng = base_deploy::new($hostname, $ip);
   if (!defined $deployMng)
   {
      baselog($LOG_ERROR, 'Cannot create deploy object.');
      update_section($cfg_file, $DEPERRORPATH, 'PREP');
      reset_status($cfg_file);
      return $ERROR;
   } ## end if (!defined $deployMng...

   my $deploy_cmd = undef;
   if ($mode eq $DEPLOYMODE{DM})
   {
      $deploy_cmd = "$RMT_SYSBACKUP_CMD --upgrade";
   }
   else
   {
      $deploy_cmd = "$RMT_SYSBACKUP_CMD  -b -noninteractive -auto -sftp $host -path $path -pwd $pwd -user $user";
   }
   baselog($LOG_DEBUG, "Remote command is '$deploy_cmd'.");
   baselog($LOG_INFO,  "Uploading 'deployment.xml' file to the target host.");
   if (!$deployMng->transfer_deploy_xml())
   {
      baselog($LOG_ERROR, "Fail to upload 'deployment.xml' file to the target host.");
      $retval = $ERROR;
   }
   else
   {
      baselog($LOG_INFO, "'deployment.xml' file successfully uploaded to the target host.");
   }
   my $deploy_call = $deployMng->call_remote_cmd($deploy_cmd);

   if ((!defined $deploy_call) or ($deploy_call ne $OK))
   {
      baselog($LOG_ERROR, 'Backup failed.');
      if (!$deployMng->retrieve_deploy_xml())
      {
         baselog($LOG_ERROR, 'Fail to get remote deployment.xml file.');
         update_section($cfg_file, $DEPERRORMSGPATH, 'Cannot synchronize status.', $KEEPOLDCNT);
      }

      if (!$deployMng->update_deploy_error('BKUP', $KEEPOLDCNT))
      {
         baselog($LOG_ERROR, 'Cannot update error code in the deployment.xml file.');
      }
      if ($mode eq $DEPLOYMODE{DM})
      {
         my $rm_backup = $deployMng->call_remote_cmd("$RM -rf $UPGRADE_BACKUP");
         if ((!defined $rm_backup) or ($rm_backup eq $ERROR))
         {
            baselog($LOG_ERROR, "Cannot remove backup archive from target host");
         }
      } ## end if ($mode eq $DEPLOYMODE...

      # check if operation status set correctly
      reset_status($cfg_file);
      update_section($cfg_file, $DEPERRORMSGPATH, 'Remote operation on the target server is failed.', $KEEPOLDCNT);
      undef $deployMng;
      return $ERROR;
   } ## end if ((!defined $deploy_call...

   if (!$deployMng->retrieve_deploy_xml())
   {
      baselog($LOG_ERROR, 'Fail to get remote deployment.xml file.');
      update_section($cfg_file, $DEPERRORMSGPATH, 'Cannot synchronize status.', $KEEPOLDCNT);
      $retval = $ERROR;
   } ## end if (!$deployMng->retrieve_deploy_xml...

   if ($mode eq $DEPLOYMODE{DM})
   {
      my $deployMngFresh = base_deploy::new($hostname, $ip);
      my $file_name = $deployMngFresh->get_param('lastBackupName');
      undef $deployMngFresh;

      if ((!defined $file_name) or ($file_name eq ''))
      {
         baselog($LOG_ERROR, 'Cannot define generated backup archive name.');
         update_section($cfg_file, $DEPERRORMSGPATH, 'Cannot define generated backup archive name.', $KEEPOLDCNT);
         $restored = $FALSE;
         $retval   = $ERROR;
      } ## end if ((!defined $file_name...
      else
      {
         $file = $path . '/' . $file_name;
         unless ($deployMng->transfer_file($UPGRADE_BACKUP, $file, $FALSE))
         {
            baselog($LOG_ERROR, 'Cannot upload backup archive from the target.');
            update_section($cfg_file, $DEPERRORMSGPATH, 'Cannot upload backup archive from the target.', $KEEPOLDCNT);
            $restored = $FALSE;
            $retval   = $ERROR;
         } ## end unless ($deployMng->transfer_file...
      } ## end else [ if ((!defined $file_name...
      my $rm_backup = $deployMng->call_remote_cmd("$RM -rf $UPGRADE_BACKUP");
      if ((!defined $rm_backup) or ($rm_backup eq $ERROR))
      {
         baselog($LOG_ERROR, 'Cannot remove backup archive from target host');
      }
   } ## end if ($mode eq $DEPLOYMODE...

   if (!$restored)
   {
      if (!$deployMng->update_deploy_error('BKUP', $KEEPOLDCNT))
      {
         baselog($LOG_ERROR, 'Cannot update error code in the deployment.xml file.');
      }
   } ## end if (!$restored)

   # check if operation status set correctly
   reset_status($cfg_file);
   if (!$deployMng->transfer_deploy_xml())
   {
      baselog($LOG_ERROR, "Fail to synchronize 'deployment.xml' file with the target host.");
   }
   undef $deployMng;

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