#!/usr/bin/perl
## @file    rmtHostDeploy
# @brief    Remote host deploy
# @details  Successful operation returns 0, otherwise 1 will be returned.
# @param    -hostname key - indicates that the next param is target host name
# @param    Target hostname to deploy
# @param    -restore  key - this key indicates that restore data should not be
#                           removed
# @param    -prepare  key - this key requires preparation work before deploy.
# @author   Ekaterina Bazhanova
# @date     April 2008
# @version  1.00 - Initial version
# @version  1.01 - Two colons were removed before shared functions and variables.
# @version 1.10 - deployment status sync is updated.
# @version 1.11 - rmtHostDeploy function has been updated( get_rmt_archive_data function call has been added).
# @version 1.12 - rmtHostDeploy function has been updated(move check -restore key after check -prepare key).
# @version 1.13 - update_section function call is updated to keep old data as well. 
# @version 1.14 - End section is updated to keep main function return code.
# @version 1.15 - rmtHostDeploy function has been updated (extracts the keycode archive).
# @version 1.16 - signals_ignore() usage added to ignore connection lost on the target side

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

use strict;
use warnings;
use common_variables;
use common_functions;
use base_deploy;
use base_system;
use appinstall::errors;
use Getopt::Long;
use recovery::backup;
use baselog;

my $operation = undef; # Operation type

## @skipline
sub rmtHostDeploy();

exit(rmtHostDeploy());

sub END
{

   # end section should not change actual return value
   # got from main function.
   my $return_val = $?;

   # re-sync deployment parameters with baseOs.properties file
   # update current deployment.xml file with accurate data
   if ((! defined $operation) and (!base_deploy::op_stat_sync()))
   {
      baselog($LOG_WARNING, "Failed to sync deployment status data.");
   }

   $? = $return_val;
} ## end sub END

###############################################################################
## @fn rmtHostDeploy()
# @brief     Main function.
# @details   1) If rmtHostDeploy was started with -hostname key only,
#            this function invokes "appinstall -deploy".  It removes all rpms
#            from /var/opt/nortel/deployed/<hostname>/install after appinstall
#            is finished. If appinstall is finished successfully, then
#            deployment.xml and baseOs.properties files are updated with
#            "deployed" status and returns 0. Otherwise it updates with
#            "undeployed" status, put error description returned
#            by appinstall to the <error> section, removes the install.xml file
#            and returns 1.
#            2) If rmtHostDeploy was started with -hostname and -prepare keys,
#            this function prepare deployment directory to deploy and exit.
#            3) If rmtHostDeploy was started with -restore key and
#            with keys from first or second case, this function does not removed
#            restore data and continue working as at first case or at second
#            case.
# @return    $OK(0)  - if appinstall was finished successfully
# @return    $ERROR(1)  - if appinstall was not finished successfully
# @author    Ekaterina Bazhanova
# @date      April 2008
# @note      None.
###############################################################################
sub rmtHostDeploy()
{
   baselog($LOG_INFO, 'Blocking signals.');
   signals_ignore();

   my $deployed_version = 'undefined version';
   my $appinstall_out;
   my $error_abbr;
   my $load;
   my $retval = $OK;

   #   script options
   my $hostname = '';
   my $restore  = '';
   my $prepare  = '';
   baselog($LOG_INFO, "rmtHostDeploy is started with the following options: @ARGV");

   GetOptions(
              "hostname=s" => \$hostname,
              "restore"    => \$restore,
              "prepare"    => \$prepare
             );

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

   # check -prepare key
   # if key exists do preparation work and exit
   # otherwise continue remote host deploy
   if ($prepare)
   {
      $operation = $prepare;
      if (base_deploy::prepare_deploy_dir($hostname))
      {
         baselog($LOG_INFO, 'Deployment directory has been prepared for deploy successfully');
         $retval = $OK;
      }
      else
      {
         baselog($LOG_ERROR, 'Deployment directory has not been prepared for deploy');
         $retval = $ERROR;
      }
      return $retval;
   } ## end if ($prepare)

   # check -restore key
   unless ($restore)
   {
      unless (removeUpgradeBackup())
      {
         baselog($LOG_ERROR, 'Cannot remove upgrade data');
         return $ERROR;
      }
   } ## end unless ($restore)

   my $deployMng = base_deploy::new($hostname);
   if (!defined $deployMng)
   {
      baselog($LOG_ERROR, 'Cannot create deploy object.');
      return $ERROR;
   }

   # continue remote host deploy
   my $cfg_file       = get_deploy_cfg_path($hostname);
   my $deployment_dir = $deployMng->{'installHome'};

   $load = $deployMng->get_param($DEPLVER);

   unless ($load)
   {
      baselog($LOG_ERROR, 'Cannot get version to deploy from deployment.xml file');
      update_section($cfg_file, "/target/errorMsg", 'Cannot check application version to deploy.', $KEEPOLDCNT);
      undef $deployMng;
      return $ERROR;
   } ## end unless ($load)

   if (!get_rmt_archive_data("$deployMng->{'installHome'}/$PRECONFIGARCH", $deployMng->{'deploymentHome'}))
   {
      baselog($LOG_ERROR, 'Cannot get pre-config data.');
      update_section($cfg_file, "/target/errorMsg", 'Cannot get pre-configuration data.', $KEEPOLDCNT);
      if (!$deployMng->update_deploy_error('PRECFG'))
      {
         baselog($LOG_ERROR, "Failed to update error section with new value ('PRECFG') for '$hostname' host.");
      }
      undef $deployMng;
      return $ERROR;
   } ## end if (!$deployMng->get_rmt_preconfig_data...

   if (!get_rmt_archive_data("$deployMng->{'installHome'}/$LICENSEARCH",$deployMng->{'installHome'}))
   {
      baselog($LOG_ERROR, 'Cannot get license data.');
      update_section($cfg_file, "/target/errorMsg", 'Cannot get license data.', $KEEPOLDCNT);
      if (!$deployMng->update_deploy_error('LICNS'))
      {
         baselog($LOG_ERROR, "Failed to update error section with new value ('LICNS') for '$hostname' host.");
      }
      undef $deployMng;
      return $ERROR;
   } ## end if (!$deployMng->get_rmt_license_data...

   if (!get_rmt_archive_data("$deployMng->{'installHome'}/$KEYCODEARCH",$deployMng->{'deploymentHome'}))
   {
      baselog($LOG_ERROR, 'Cannot get keycode file.');
      update_section($cfg_file, "/target/errorMsg", 'Cannot get keycode file.', $KEEPOLDCNT);
      if (!$deployMng->update_deploy_error('KEYCD'))
      {
         baselog($LOG_ERROR, "Failed to update error section with new value ('KEYCD') for '$hostname' host.");
      }
      undef $deployMng;
      return $ERROR;
   } ## end if (!$deployMng->get_rmt_keycode_file...


   #invoke "appinstall -deploy"
   if (do_system([$SUDO, $SUDO_NORTEL, $APP_DEPLOY, '-deploy', $deployment_dir], {$dsRETVAL => \$appinstall_out}))
   {
      baselog($LOG_INFO, 'Applications were installed successfully.');
      $retval = $OK;
   }
   else
   {
      baselog($LOG_ERROR, 'Cannot deploy applications.');
      $retval = $ERROR;
   } ## end else [ if (do_system([$SUDO, ...

   # updating deployment status in baseOS.properties file
   change_deploy_status($hostname);

   #checking error code from appinstall
   $error_abbr = appinstall::errors::error_decoder($appinstall_out);
   unless ($error_abbr)
   {
      baselog($LOG_ERROR, 'Appinstall error code is undefined');
      $retval = $ERROR;
   }

   $error_abbr = '' if ($error_abbr eq 'NULL');
   if (!$deployMng->update_deploy_error($error_abbr))
   {
      baselog($LOG_ERROR, "Failed to update error section with new value ($error_abbr) for '$hostname' host.");
      $retval = $ERROR;
   }

   #remove all rpms from /var/opt/nortel/deployed/<hostname>/install after appinstall is finished
   if (base_deploy::clean_up($hostname))
   {
      baselog($LOG_INFO, 'Deployment directory was cleared');
   }
   else
   {
      baselog($LOG_ERROR, 'Cannot clear deployment directory');
   }
   undef $deployMng;
   return $retval;
} ## end sub rmtHostDeploy()

