#!/usr/bin/perl
## @file appRestore
# @brief It restore applications to the target LinuxBase server.
# @details  Successful operation returns 0, otherwise 1 will be returned.
# @param hostname - target hostname to deploy (key parameter to find the data
#                    related to the deployment operation).
# @param IP - ip-address of the target host
# @param mode - restore method ('DM' - Deployment Manager, 'BS' - Backup Server)
# @param host - backup server IP
# @param file - absolute restore achive file name on the backup server
# @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 - Restore operation status update is changed.
# @version 1.11 - Modified update_section function call to keep all error messages
# @version 1.12 - Modified appRestore function to synchronize deployment.xml file with target
# @version 1.13 - prepare_restore() function is added
# @version 1.14 - Updated log records with hostname and IP information.
# @version 1.15 - New "-force" option support is added to allow to restore data even if
#                 application version or supported configuration mismatch found.
# @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;
use File::Basename;

## @skipline
sub appRestore();
## @skipline
sub prepare_restore($);

our $hostname        = undef;
our $ip              = undef;
our $mode            = undef;
our $host            = undef;
our $file            = undef;
our $user            = undef;
our $pwd             = undef;
our $cfg_file        = undef;
our $mismatch_ignore = undef;

exit(appRestore());

###############################################################################
## @fn appRestore()
# @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   $file - 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 appRestore()
{
   GetOptions(
              "hostname:s" => \$hostname,
              "IP:s"       => \$ip,
              "mode:s"     => \$mode,
              "host:s"     => \$host,
              "file:s"     => \$file,
              "user:s"     => \$user,
              "pwd:s"      => \$pwd,
              "force"      => \$mismatch_ignore
             );

   my $retval = $OK;

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

   $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 restore 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, 'Restore method is undefined');
      update_section($cfg_file, $DEPERRORPATH, 'UNMTHD');
      reset_status($cfg_file);
      return $ERROR;
   } ## end if ((!defined $mode) or...

   if ((!defined $file) or ($file 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 $file) 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...

   $retval = $ERROR;

   # check if temporary restore directory exists.
   if (!$deployMng->make_deploy_dir($TEMP_RESTORE_DIR, 'Cannot create temporary restore directory.'))
   {

      # set the flag that we don't need to perform an actions with remote side.
      $deployMng->{'operStop'} = $TRUE;
   } ## end if (!$deployMng->make_deploy_dir...
   else
   {
      my $deploy_cmd = prepare_restore($deployMng);
      if (defined $deploy_cmd)
      {

         #push deployment.xml file to the target
         baselog($LOG_INFO, "Uploading 'deployment.xml' file to the '$hostname [$ip]' host.");
         if (!$deployMng->transfer_deploy_xml())
         {
            baselog($LOG_ERROR, "Fail to upload 'deployment.xml' file to the '$hostname [$ip]' host.");
            if (!$deployMng->update_deploy_error('RESF'))
            {
               baselog($LOG_ERROR, 'Cannot update error in the deployment.xml file.');
            }
         } ## end if (!$deployMng->transfer_deploy_xml...
         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)
            {
               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 ($deploy_call ne $OK)
               {
                  baselog($LOG_ERROR, 'Restore failed.');
                  if (!$deployMng->update_deploy_error('RESF', $KEEPOLDCNT))
                  {
                     baselog($LOG_ERROR, 'Cannot update error in the deployment.xml file.');
                  }
                  update_section($cfg_file, $DEPERRORMSGPATH, 'Remote operation on the target server is failed.', $KEEPOLDCNT);
               } ## end if ($deploy_call ne $OK...
               else
               {
                  baselog($LOG_INFO, 'Restore successfully completed.');
                  $retval = $OK;
               }
            } ## end if (defined $deploy_call...
         } ## end else [ if (!$deployMng->transfer_deploy_xml...
      } ## end if (defined $deploy_cmd...
      else
      {
         $deployMng->{'operStop'} = $TRUE;
      }

   } ## end else [ if (!$deployMng->make_deploy_dir...

   # check if operation status set correctly
   reset_status($cfg_file);

   # if operation was not stopped then
   #push clean deployment.xml to the target to reset operation status.
   if ((!$deployMng->{'operStop'}) and (!$deployMng->transfer_deploy_xml()))
   {
      baselog($LOG_ERROR, "Fail to synchronize 'deployment.xml' file with the target host.");
   }

   undef $deployMng;
   return $retval;
} ## end sub appRestore()

###############################################################################
## @fn prepare_restore($deployMng)
# @brief   It generates restore command depend on the selected mode. And it
# transfers restore archive file to the  target in case of DM mode.
# @details None.
# @param   $deployMng - deployment object.
# @return  $deploy_cmd - generated restore command.
# @return  undef -  indicates an error condition.
sub prepare_restore($)
{
   my ($deployMng) = @_;
   my $cmd;

   if (!defined $deployMng)
   {
      baselog($LOG_ERROR, 'Deployment object is not defined.');
      return undef;
   }

   my $restore_file = basename($file);

   if (!$restore_file)
   {
      baselog($LOG_ERROR, 'Cannot define restore archive file name.');
      update_section($cfg_file, $DEPERRORPATH, 'RESF');
      return undef;
   } ## end if (!$restore_file)

   my $local_restore_file = $TEMP_RESTORE_DIR . '/' . $restore_file;
   my $deploy_cmd         = undef;

   #prepare restore command
   #for DM mode push restore archive to the target first.
   if ($mode eq $DEPLOYMODE{DM})
   {
      unless ($deployMng->transfer_file($file, $TEMP_RESTORE_DIR))
      {
         baselog($LOG_ERROR, 'Cannot transfer restore archive to the target.');
         update_section($cfg_file, $DEPERRORPATH, 'TRNSF');
         return undef;
      } ## end unless ($deployMng->transfer_file...

      $deploy_cmd = "$RMT_SYSRESTORE_CMD -noninteractive -file $local_restore_file";
      baselog($LOG_DEBUG, "Remote command is '$deploy_cmd'.");
   } ## end if ($mode eq $DEPLOYMODE...
   else
   {
      $deploy_cmd = "$RMT_SYSRESTORE_CMD -noninteractive -auto -sftp $host -file $file -dst $local_restore_file -pwd $pwd -user $user";
      baselog($LOG_DEBUG, "Remote command is '$deploy_cmd'.");
   }

   if ($mismatch_ignore)
   {
      $deploy_cmd .= ' -force';
      baselog($LOG_INFO, 'Force recovery requested.');
   }

   return $deploy_cmd;
} ## end sub prepare_restore($)
