#!/usr/bin/perl    
## @file sysrestore
# @brief Perform system restoration (both base and applications).
# @details This script restores application backed up data into default directory and
#          executes restore scripts for installed applications (if such are defined).
#
# @param $noninteractive  - noninteractive mode
# @param $auto  - auto sftp usage mode (this mode indicate the noninteractive connection via sftp)
# @param $file  - absolute path to the restore archive (use with noninteractive and auto modes)
# @param $user  - backup user ID (use with auto mode)
# @param $sftp  - backup server IP (use with auto mode)
# @param $pwd   - not encrypted backup user password (use with auto mode)
# @param $dst   - path where to put restore archive on the target (use with auto mode)
# @return $OK    - OK
# @return $ERROR - ERROR
#
# @author Kate Bereznyakova
# @date October 2006
#
# @version 1.00 - Initial version
# @version 1.01 - reworking semaphore stuff
# @version 1.02 - using base_system is added - system() invocations replaced with do_system
# @version 1.03 - POD section was added; the usage is displayed by the common function print_pod_usage() now.
# @version 1.04 - start/stop of the Applications is separated into Nortel and Base
# @version 1.05 - The following input params was added: noninteractive, auto, file, user, sftp, pwd, dst.
#                 Code was modified for using noninteractive and auto modes.
# @version 1.06 - Two colons were removed before shared functions and variables.
# @version 1.07 - Functions collectSFTPInfo() and restore_app() have been modified
#                 to set up error message to deployment configuration file
# @version 1.08 - update main function to fill <lastRestoreTime> tag in deployment.xml file
# @version 1.09 - Function get_hostname is now used instead of Sys::Hostname
# @version 1.10 - $ENV{'PATH'} is now patched to contain /bin under restricted shell ('tar' command requires it).
# @version 1.11 - New function remove_restore_archive() is added to remove temporary restore archives.
# @version 1.12 - Parsing the network conf files is removed from get_SFTP_file() function.
# @version 1.13 - Doxygen comments has been added
# @version 1.14 - 770 permissions for /admin/nortel/restore/ are now used
# @version 1.2 - Restore logic is changed to stop Applications after restore archive is
#                available on the system.
#   @li DM_mode flag is added to skip DM related steps in CLI mode
#   @li get_restore_archive() - new function
#   @li get_restore_archive_interactive()  - new function
#   @li get_restore_archive_noninteractive() - new function.
# @version 1.25 - New "-force" option support is added to allow to restore data even if
#                 application version or supported configuration mismatch found. This option for DM mode only.
# @version 1.30 - Function remove_restore_archive() is updated to reset deployment status.
# @note

=pod

=head1 NAME

B<sysrestore> - Restore data from the backup archive.

=head1 SYNOPSIS

B<sysrestore> [B<--help>]

=head1 DESCRIPTION

This script retrieves the backup archive from the storage (USB device
or SFTP server), restores application backed up data into the default
backup directory and executes the restore scripts for installed
applications (if they are defined).
  Note: sysrestore would not restore the Linux Base Configuration Data:
        Network Configuration
        Time Zone Configuration
        NTP Configuration
        DNS Configuration
        Local Accounts (root & admin2) Passwords

=head1 OPTIONS

=over 4

=item B<--help>

Print this help message and exit.

=back

=cut

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

use warnings;
use strict;

use common_variables;
use common_functions;
use Data::Dumper;
use Net::SFTP;
use recovery::backup;
use baselog;
use base_semctl;
use base_system;
use base_deploy;
use Getopt::Long;
use CommonInstallUtils;

my %ftpData;
my $noninteractive  = $FALSE;
my $auto            = $FALSE;
my $file            = undef;
my $user            = undef;
my $pwd             = undef;
my $sftp            = undef;
my $dst             = undef;
my $hostname        = undef;
my $cfg_file        = undef;
my $mismatch_ignore = undef;

my $undefined_app_info = 'undefined';
my $DM_mode            = $FALSE;

# @skipline
sub sysrestore();  #entry point

# @skipline
sub get_SFTP_file(@);  #Select and download backup archive form SFTP-server
## @skipline
sub collect_SFTP_info();  #function to get all parameters to access to SFTP-server's backup storage

# @skipline
sub restore_app($);       #general function with user interface
## @skipline
sub remove_restore_archive();  #removes temporary restore archive
## @skipline
sub get_restore_archive_interactive();
## @skipline
sub get_restore_archive_noninteractive();
## @skipline
sub get_restore_archive();

exit(sysrestore());

###############################################################################
## @fn sysrestore()
# @brief   Main function (entry point)
# @return $OK    - OK
# @return $ERROR - ERROR

sub sysrestore()
{
   if (warning_if_not_nortel_grp())
   {
      remove_restore_archive();
      return $ERROR;
   }

   if (defined $ARGV[0] and $ARGV[0] =~ /help$/)
   {
      print_pod_usage();
      return $OK;
   }
   GetOptions(
              "noninteractive" => \$noninteractive,
              "auto"           => \$auto,
              "sftp:s"         => \$sftp,
              "dst:s"          => \$dst,
              "user:s"         => \$user,
              "pwd:s"          => \$pwd,
              "file:s"         => \$file,
              "force"          => \$mismatch_ignore
             );

   my $retval  = $ERROR;
   my $scripts = undef;

   my @semlist = ($SEM_BACKUP, $SEM_APPSTART, $SEM_HARD);
   baselog($LOG_INFO, "Sysrestore started.\n");

   signals_ignore();
   recover_env_path();

   #set up flag for DM related actions
   if ($noninteractive)
   {
      $DM_mode  = $TRUE;
      $hostname = get_hostname();
      $cfg_file = get_deploy_cfg_path($hostname);
      baselog($LOG_INFO, "Operation started in non-interactive mode.");
   } ## end if ($noninteractive)

   # create semaphore manager object
   my $semmngr = base_semctl::new($SBS_SYSRESTORE);
   if (!defined($semmngr))
   {
      my $error_descr = $!;
      baselog($LOG_ERROR, "Cannot create semaphore manager object ($error_descr).");
      baselog($LOG_ERROR, "Restore failed.\n", !$noninteractive);
      remove_restore_archive();
      return $ERROR;
   } ## end if (!defined($semmngr)...

   if (!$semmngr->sem_take(\@semlist, IPC_NOWAIT))
   {
      undef $semmngr;
      baselog($LOG_ERROR, "Restore operation aborted.\n", !$noninteractive);
      if ($DM_mode)
      {
         update_section($cfg_file, $DEPERRORPATH, 'RSBLK');
      }
      remove_restore_archive();
      return $ERROR;
   } ## end if (!$semmngr->sem_take...

   unless (do_system([$SUDO, $SUDO_NORTEL, $CLEAR_BACKUP]))
   {
      baselog($LOG_ERROR, "Cannot clean up backup directory.\n", !$noninteractive);
   }
   else
   {
      my $archive = get_restore_archive();
      if ((!defined $archive) or ($archive eq ""))
      {
         baselog($LOG_ERROR, "Cannot get backup archive for recovery.\n", !$noninteractive);
         $retval = $ERROR;
      }
      elsif (not -e $archive)
      {
         baselog($LOG_ERROR, "Failed to get backup archive for recovery.\n", !$noninteractive);
         $retval = $ERROR;
      }
      else
      {
         if (check_installedconfig($archive) == $TRUE)
         {

            #backup archive is available for recovery now. Start recovery step.
            baselog($LOG_INFO, "All Nortel and Base applications will be stopped.\n", !$noninteractive);
            if ($noninteractive or getYNResponse("Do you want to continue", 'Y'))
            {
               if (!$noninteractive)
               {
                  print "*** Stopping Applications ...\n";
               }

               if (do_system([$SUDO, $SUDO_NORTEL, $APP_SERVICE, $SRV_STOP], {$dsINTERACT => !$noninteractive}))
               {
                  if (do_system([$SUDO, $SUDO_NORTEL, $APP_SERVICE, $BASE_APPS, $SRV_STOP], {$dsINTERACT => !$noninteractive}))
                  {
                     if (!restore_app($archive))
                     {
                        baselog($LOG_ERROR, 'Restore failed.');
                        if (!$noninteractive)
                        {
                           header("\nRestore failed", $TRUE);
                        }
                     } ## end if (!restore_app($archive...
                     else
                     {
                        $retval = $OK;
                     }
                     if (!$noninteractive)
                     {
                        print "*** Starting Applications ...\n";
                     }

                     if (do_system([$SUDO, $SUDO_NORTEL, $APP_SERVICE, $BASE_APPS, $SRV_START], {$dsINTERACT => !$noninteractive}))
                     {
                        unless (do_system([$SUDO, $SUDO_NORTEL, $APP_SERVICE, $SRV_START], {$dsINTERACT => !$noninteractive}))
                        {
                           baselog($LOG_ERROR, "Nortel Applications could not be started.\n", !$noninteractive);
                        }
                     } ## end if (do_system([$SUDO, ...
                     else
                     {
                        baselog($LOG_ERROR, "Base Applications could not be started.\n", !$noninteractive);
                     }
                  } ## end if (do_system([$SUDO, ...
                  else
                  {
                     baselog($LOG_ERROR, "Base Applications could not be stopped.\n", !$noninteractive);
                     if ($DM_mode)
                     {
                        update_section($cfg_file, $DEPERRORMSGPATH, 'Applications could not be stopped. Please restart the applications.', $KEEPOLDCNT);
                     }
                  } ## end else [ if (do_system([$SUDO, ...
               } ## end if (do_system([$SUDO, ...
               else
               {
                  baselog($LOG_ERROR, "Nortel Applications could not be stopped.\n", !$noninteractive);
                  if ($DM_mode)
                  {
                     update_section($cfg_file, $DEPERRORMSGPATH, 'Nortel Applications could not be stopped.', $KEEPOLDCNT);
                  }
               } ## end else [ if (do_system([$SUDO, ...
            } ## end if ($noninteractive or...
            else
            {
               baselog($LOG_INFO, 'Sysrestore interrupted by user.');
            }
         } ## end if (check_installedconfig...
         else
         {
            baselog($LOG_ERROR, "Installed config does not match to backup one or it cannot be checked. Recovery canceled.");
         }
      } ## end else [ if ((!defined $archive...

   } ## end else

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

   # destroy the object
   undef $semmngr;
   baselog($LOG_INFO, "Sysrestore finished.\n");

   if (($retval eq $OK) and $DM_mode)
   {
      my ($sec, $min, $hour, $mday, $mon, $year) = localtime();
      my $date = sprintf("%04d_%02d_%02d-%02d_%02d_%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec);
      if (!update_section($cfg_file, "/target/lastRestoreTime", $date))
      {
         baselog($LOG_INFO, 'Cannot update the deployment.xml file.');
      }
   } ## end if (($retval eq $OK) and...

   remove_restore_archive();

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

#####################################################################
#                           Subroutines                             #
#####################################################################
###############################################################################
## @fn restore_app($archive)
# @brief   Restore operation
# @details Restore operation that executes restore scripts
## @param  $archive - archive to use as restore data source
# @return  $TRUE - if restore successfully completed.
# @return  $FALSE - if restore failed.

sub restore_app($)
{
   my $archive = shift @_;
   my $retval  = $FALSE;
   if (do_system([$TAR, '--directory=/', '-Pxzf', $archive]))
   {
      do_system([$SUDO, $SUDO_NORTEL, $EXECUTE_SCRIPTS, $RESTORE_SCRIPTS], {$dsINTERACT => !$noninteractive});
      baselog($LOG_INFO, 'Restore completed.');
      if (!$noninteractive)
      {
         header("\nRestore completed", $TRUE);
      }
      $retval = $TRUE;
   } ## end if (do_system([$TAR, '--directory=/'...
   else
   {
      if ($DM_mode)
      {
         update_section($cfg_file, $DEPERRORMSGPATH, 'Cannot extract data from backup archive.', $KEEPOLDCNT);
      }
      baselog($LOG_ERROR, 'Cannot extract backup data.');
      $retval = $FALSE;
   } ## end else [ if (do_system([$TAR, '--directory=/'...

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

###############################################################################
## @fn check_installedconfig($archive)
# @brief Check whether backup have done for the same configuration as installed one
# @param  $archive - path to downloaded backup archive (including name)
# @return $TRUE - configurations match or user confirm usage of this backup
#         archive or there is no backup configuration file
# @return $FALSE - configurations do not match
sub check_installedconfig($)
{
   my $archive = shift @_;
   my $retval  = $FALSE;

   my ($app_backed_up, $backup_version) = getBackupConfiguration($archive);
   if (!$app_backed_up)
   {
      $app_backed_up = $undefined_app_info;
      return $TRUE;
   }
   if (!$backup_version)
   {
      $backup_version = $undefined_app_info;
      return $TRUE;
   }

   # get current configuration
   my $params = use_confver($CONFVER);
   my ($app_installed, $app_version) = ($undefined_app_info, $undefined_app_info);
   if ($params)
   {
      if ($params->{'APP_INSTALLED'})
      {
         $app_installed = $params->{'APP_INSTALLED'};
      }
      if ($params->{'APP_VERSION'})
      {
         $app_version = $params->{'APP_VERSION'};
      }
   } ## end if ($params)

   #check if configurations match
   if ($app_backed_up ne $app_installed)
   {

      #if backup was done on the "clean base" that it's ok
      if ($app_backed_up eq $undefined_app_info)
      {
         $retval = $TRUE;
      }
      else
      {
         baselog($LOG_INFO, "Backup was done for $app_backed_up configuration.\n", !$noninteractive);

         if ($app_installed ne $undefined_app_info)
         {
            baselog($LOG_INFO, "Current configuration is $app_installed.\n", !$noninteractive);
            baselog($LOG_INFO, "Restore can corrupt existing data.\n",       !$noninteractive);
         }
         else
         {
            baselog($LOG_INFO, "You have no installed applications.\n", !$noninteractive);
         }

         if ($noninteractive)
         {
            if ($mismatch_ignore)
            {
               update_section($cfg_file, $DEPERRORMSGPATH, "Warning:  Trying to use mismatch data to restore - $app_backed_up [Installed configuration: $app_installed].", $KEEPOLDCNT);
               $retval = $TRUE;
            }
            else
            {
               update_section($cfg_file, $DEPERRORMSGPATH, "Incorrect configuration in backup archive:  $app_backed_up [Installed configuration: $app_installed]. Cannot use this archive to restore.",
                              $KEEPOLDCNT);
               update_section($cfg_file, $DEPERRORPATH, 'WAPPVER');
               $retval = $FALSE;
            } ## end else [ if ($mismatch_ignore)
         } ## end if ($noninteractive)
         elsif (getYNResponse("Do you want to continue", 'N'))
         {
            $retval = $TRUE;
         }
      } ## end else [ if ($app_backed_up eq ...

      #check if versions match
   } ## end if ($app_backed_up ne ...
   elsif ($backup_version ne $app_version)
   {

      #if backup was done on the "clean base" that it's ok
      if ($backup_version eq $undefined_app_info)
      {
         $retval = $TRUE;
      }
      else
      {
         baselog($LOG_INFO, "Backup was done for version $backup_version.\n", !$noninteractive);
         if ($app_version ne $undefined_app_info)
         {
            baselog($LOG_INFO, "Current version is $app_version.\n",   !$noninteractive);
            baselog($LOG_INFO, "Restore can corrupt existing data.\n", !$noninteractive);
         }
         else
         {
            baselog($LOG_INFO, "You have no installed applications.\n", !$noninteractive);
         }

         if ($noninteractive)
         {
            if ($mismatch_ignore)
            {
               update_section($cfg_file, $DEPERRORMSGPATH, "Warning:  Trying to use mismatch data to restore - $backup_version [Installed version: $app_version].", $KEEPOLDCNT);
               $retval = $TRUE;
            }
            else
            {
               update_section($cfg_file, $DEPERRORMSGPATH, "Incorrect version in the backup archive:  $backup_version [Installed version: $app_version]. Cannot use this archive to restore.",
                              $KEEPOLDCNT);
               update_section($cfg_file, $DEPERRORPATH, 'WAPPVER');
               $retval = $FALSE;
            } ## end else [ if ($mismatch_ignore)
         } ## end if ($noninteractive)
         elsif (getYNResponse("Do you want to continue", 'N'))
         {
            $retval = $TRUE;
         }
      } ## end else [ if ($backup_version eq...
   } ## end elsif ($backup_version ne...
   else
   {
      $retval = $TRUE;
   }

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

###############################################################################
## @fn get_SFTP_file(@)
# @brief   Select and download the backup archive from SFTP-server
# @param   $restore_archive - path where to put downloaded backup archive (including name)
# @param   $log - file where error messages should be put
# @return  $restore_archive - path to downloaded archive
#          if error occurred then this value will be empty

sub get_SFTP_file(@)
{
   my ($restore_archive, $log) = @_;
   my $config = $fsbackup_config_script . "SFTP";
   if (-e $config)
   {
      require $config;
      if (defined($::cfg_remote_host))
      {
         $ftpData{'remoteIP'} = $::cfg_remote_host;
      }
      if (defined($::cfg_remote_login))
      {
         $ftpData{'user'} = $::cfg_remote_login;
      }
      if (defined($::cfg_remote_path))
      {
         $ftpData{'remoteDir'} = $::cfg_remote_path;
      }

   } ## end if (-e $config)

   if (collect_SFTP_info() == $TRUE)
   {
      $restore_archive = getSFTPArchive($restore_archive, %ftpData);
   }
   return $restore_archive;
} ## end sub get_SFTP_file(@)

###############################################################################
## @fn collect_SFTP_info()
# @brief  To collect information for SFTP connection
# @return  $TRUE  - operation succeed
# @return  $FALSE - error occurred
sub collect_SFTP_info()
{
   my $retval = $FALSE;

   # see if we have any default values
   my $is_exit = $FALSE;
   while (($is_exit == $FALSE) && (!$auto))
   {

      # 1) get remote machine ip
      # 2) get remote sftp username
      # 3) get remote sftp password
      # 4) get remote directory
      #
      $ftpData{'remoteIP'} = craphack(getValidIP("Enter the secure FTP server's IP address", $ftpData{'remoteIP'}));
      $ftpData{'user'} = craphack(getLogin("Enter the SFTP login", $ftpData{'user'}));

      # Password should be hidden. Do not show this input
      system($STTY, '-echo');
      $ftpData{'passwd'} = craphack(getTextResponse("Enter the SFTP password", ""));
      system($STTY, 'echo');

      #as input for password was not out to screen so new line symbol should be added
      print "\n";
      $ftpData{'remoteDir'} = craphack(getTextResponse("Enter the remote SFTP directory", $ftpData{'remoteDir'}));

      if (validateRemoteCIQInfo(%ftpData))
      {
         $retval  = $TRUE;
         $is_exit = $TRUE;
      }
   } ## end while (($is_exit == $FALSE...

   if ($auto)
   {
      if ((!defined $user) or ($user eq ''))
      {
         baselog($LOG_ERROR, 'Backup user ID is undefined.');
         return $FALSE;
      }
      if ((!defined $sftp) or ($sftp eq ''))
      {
         baselog($LOG_ERROR, 'Backup ip address is undefined.');
         return $FALSE;
      }
      if (!defined $pwd)
      {
         baselog($LOG_ERROR, 'Backup user password is undefined.');
         return $FALSE;
      }
      $ftpData{'remoteIP'}       = $sftp;
      $ftpData{'user'}           = $user;
      $ftpData{'passwd'}         = $pwd;
      $ftpData{'remoteDir'}      = $1 if $file =~ /^(.*)\/(.*)/;
      $ftpData{'archname'}       = $2 if $file =~ /^(.*\/)(.*)/;
      $ftpData{'noninteractive'} = $noninteractive;
      $retval                    = $TRUE;
   } ## end if ($auto)
   if (!do_system([$PING, '-q', '-c', '3', $ftpData{'remoteIP'}]))
   {
      baselog($LOG_ERROR, "\nRemote host (SFTP server) is not accessible via Network.\n", !$noninteractive);
      if (!$noninteractive) {print "Check network configuration.\n\n";}
      if ($DM_mode)
      {
         update_section($cfg_file, $DEPERRORMSGPATH, 'SFTP server is not accessible via Network.', $KEEPOLDCNT);
      }
      $retval = $FALSE;
   } ## end if (!do_system([$PING,...
   return $retval;
} ## end sub collect_SFTP_info()

###############################################################################
## @fn cleanup()
# @brief Handler for "Ctrl+C"
sub cleanup()
{
   return;
}

###############################################################################
## @fn remove_restore_archive()
# @brief   It checks and removes temporary restore archives downloaded to the
#          system during restore operation.
# @details None.
# @return  $TRUE -  operation succeed.
# @return  $FALSE - error occurred
sub remove_restore_archive()
{
   my $retval = $TRUE;

   if ($noninteractive)
   {
      baselog($LOG_DEBUG, 'remove_restore_archive is invoked in non-interactive mode.');
      my $rmfile = '';

      #auto flag is used in SFTP mode where $dst parameter defined file name.
      if ($auto)
      {
         if (defined $dst)
         {
            $rmfile = $dst;
         }
      } ## end if ($auto)

      #if noninteractive mode is non-auto and $file parameter is defined then
      #restore archive is downloaded earlier.
      elsif (defined $file)
      {
         $rmfile = $file;
      }

      if (($rmfile ne '') and (-e $rmfile))
      {

         if (!do_system([$RM, '-rf', $rmfile]))
         {
            baselog($LOG_ERROR, "Cannot remove temporary restore file '$dst'.");
            $retval = $FALSE;
         }
      } ## end if (($rmfile ne '') and...
   } ## end if ($noninteractive)

   if ($DM_mode)
   {
      update_section($cfg_file, "/target/$DEPSTATUS", $DEPLOYSTATUS{none});
   }

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

###############################################################################
## @fn get_restore_archive()
# @brief   It gets restore archive to the system depend on the selected mode.
# @details None.
# @return  archive name or empty line on the failed condition.
sub get_restore_archive()
{
   my $retval = '';
   if (!$noninteractive)
   {
      $retval = get_restore_archive_interactive();
   }
   else
   {
      $retval = get_restore_archive_noninteractive();
   }
   return $retval;
} ## end sub get_restore_archive()

###############################################################################
## @fn get_restore_archive_noninteractive()
# @brief   It gets restore archive to the system depend on the provided
#          parameters.
# @details None.
# @return  archive name or empty line on the failed condition.
sub get_restore_archive_noninteractive()
{
   my $archive = '';
   if ((!defined $file) or ($file eq ''))
   {
      baselog($LOG_ERROR, 'Path to backup archive is undefined.');
      return $archive;
   }

   #DM-SFTP mode is indicated by "auto" keyword
   #other options assume local file usage
   if (!$auto)
   {
      return $file;
   }

   if ((!defined $dst) or ($dst eq ''))
   {
      baselog($LOG_ERROR, 'Path to backup archive on the target is undefined.');
      return $archive;
   }

   $archive = get_SFTP_file($dst);
   if (((!defined $archive) or ($archive eq '')) and ($DM_mode))
   {
      update_section($cfg_file, $DEPERRORMSGPATH, 'Cannot get backup archive from SFTP server. Please, check your input access parameters.', $KEEPOLDCNT);
   }

   return $archive;
} ## end sub get_restore_archive_noninteractive()

###############################################################################
## @fn get_restore_archive_interactive()
# @brief   It checks if restore archive is available locally by default path
#          and allows to use it. If local restore archive can not be used then
#          it tries to get data from external backup storage in the interactive
#          mode.
# @details None.
# @return  archive name or empty line on the failed condition.
sub get_restore_archive_interactive()
{

   my $archive = "";
   if (-e $restoreArchive)
   {
      print "Restore archive found in /admin directory.\n";

      if (getYNResponse("Do you want to use it", 'Y'))
      {
         return $restoreArchive;
      }

      if (!unlink($restoreArchive))
      {
         baselog($LOG_ERROR, 'Cannot remove old restore archive.');
      }
   } ## end if (-e $restoreArchive...
   else
   {
      my $restore_dir = $1 if $restoreArchive =~ /^(.*\/)(.*)/;

      if (!defined($restore_dir))
      {
         baselog($LOG_ERROR, "Restore directory $restore_dir not defined.\n", $TRUE);
         return $archive;
      }

      if (!-d $restore_dir)
      {
         unless (mkdir $restore_dir)
         {
            baselog($LOG_ERROR, "Cannot create temporary directory ($restore_dir) for restore archive. Restore stopped.\n", $TRUE);
            return $archive;
         }

         unless (chmod 0770, $restore_dir)
         {
            baselog($LOG_ERROR, "Cannot change permissions of temporary directory ($restore_dir) for restore archive. Restore stopped.\n", $TRUE);
            return $archive;
         }
      } ## end if (!-d $restore_dir)
   } ## end else [ if (-e $restoreArchive...

   my $is_end = $FALSE;
   while ($is_end == $FALSE)
   {
      print "1. Recover from USB device.\n";
      print "2. Recover from SFTP server.\n\n";
      print "Enter your choice (q for exit): ";
      chomp(my $opt = <STDIN>);
      if ($opt eq "q" or $opt eq "Q")
      {
         $is_end = $TRUE;
      }
      else
      {
         if ($opt eq "2")
         {
            $archive = get_SFTP_file($restoreArchive);
         }
         elsif ($opt eq "1")
         {
            $archive = getUSBBackupData($restoreArchive);
         }
         if ($archive ne "")
         {
            $is_end = $TRUE;
         }
      } ## end else [ if ($opt eq "q" or $opt...
   } ## end while ($is_end == $FALSE)
   return $archive;
} ## end sub get_restore_archive_interactive()
