#!/usr/bin/perl
## @file    rmtHostUpgrade
# @brief    Remote host upgrade
# @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 upgrade
# @author   Ekaterina Bazhanova
# @date     May 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 - rmtHostUpgrade function has been updated( get_rmt_archive_data function call has been added).
# @version 1.12 - End section is updated to keep main function return code.
# @version 1.13 - Operation status update to "Upgrade is in progress" is removed.
# @version 1.14 - rmtHostUpgrade function has been updated (extracts the keycode archive).
# @version 1.15 - signals_ignore() usage added to ignore connection lost on the target side

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

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

## @skipline
sub rmtHostUpgrade();
## @skipline
sub preparation($);

exit(rmtHostUpgrade());

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 (!base_deploy::op_stat_sync())
   {
      baselog($LOG_WARNING, "Failed to sync deployment status data.");
   }

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

###############################################################################
## @fn rmtHostUpgrade()
# @brief     Main function.
# @details   1) If rmtHostUpgrade was started with -hostname key only,
#            this function invokes "appinstall -upgrade".  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 rmtHostUpgrade was started with -hostname and -prepare keys,
#            this function prepare deployment directory to upgrade and exit.
# @return    $OK(0)  - if appinstall was finished successfully
# @return    $ERROR(1)  - if appinstall was not finished successfully
# @author    Ekaterina Bazhanova
# @date      May 2008

sub rmtHostUpgrade()
{
   baselog($LOG_INFO, 'Blocking signals.');
   signals_ignore();

   my $deployed_version;
   my $appinstall_out;
   my $error_abbr;
   my $retval = $OK;

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

   GetOptions("hostname=s" => \$hostname);

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

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

   my $deployment_dir = $deployMng->{'installHome'};
   my $cfg_file       = get_deploy_cfg_path($hostname);

   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.');
      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 (!get_rmt_archive_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.');
      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 (!get_rmt_archive_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 -upgrade"
   if (do_system([$SUDO, $SUDO_NORTEL, $APP_DEPLOY, '-upgrade', $deployment_dir], {$dsRETVAL => \$appinstall_out}))
   {
      baselog($LOG_INFO, 'Applications were upgraded successfully.');
   }
   else
   {
      baselog($LOG_ERROR, 'Cannot upgrade application.');
      $retval = $ERROR;
   }

   # 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;
   }

   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 rmtHostUpgrade()
