#!/bin/sh
#
# Upgrade package installer
#

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    if [ -d 'zxtm/bin' ]
    then
       ZEUSHOME=`pwd`
       export ZEUSHOME
       cd $OLD_PWD
    fi
fi

if [ ! -z "$ZEUSHOME" ]
then
   PROG=$ZEUSHOME/perl/miniperl
fi

exec $PROG -Tx $0 ${1+"$@"}
#!perl -w
#line 29

BEGIN {
   # Unset the environment variables that Perl knows can affect shell
   # behaviour, otherwise when you try to call system() Perl -T
   # (taint mode) halts, with an "Insecure $ENV{x}" message.
   delete @ENV{'ENV', 'BASH_ENV', 'CDPATH', 'IFS'};

   # Untaint ZEUSHOME
   $ENV{ZEUSHOME} = $1 if( $ENV{ZEUSHOME} =~ /^(.*)$/ );
   $ENV{PATH} = $1 if( $ENV{PATH} =~ /^(.*)$/ );
   

   unshift( @INC,
      "$ENV{ZEUSHOME}/zxtm/lib/perl",
      "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
      "$ENV{ZEUSHOME}/perl"
   );
};

use strict;

use Zeus::Session qw( createEphemeralSession );
use Zeus::ZXTM::PackageInstall qw(
   InstallPackage RunRestartScript UntarPackage
   ValidatePackage getPackageInfo FormatPackageInfo
);
use Zeus::ZInstall::Common;

if( grep( /^--?h(elp)?$/, @ARGV ) ) {
   print <<EOF;
Usage: upgrade info <package>
       upgrade install <package> [params]

Installs or prints information about a Stingray upgrade package.

Info mode:
  Prints information about the package, including the platform and version it
  is built for. It also prints what additional information the package requires
  to install. If the package is not valid for the local system it will print
  out the reason and return a exit code.

Install mode:
  Installs the package if it is valid for the local system. When installing 
  packages that require additional information you can enter this information
  in one of three ways:
    * As a parameter, e.g. --cluster-pw=<PASSWORD>
    * As a environment variable with Z_UPGRADE_ prefixed, e.g. 
      export Z_UPGRADE_CLUSTER_PW=<PASSWORD>
    * On the standard input when prompted, unless --non-interactive is set.

  If the package is not valid for the local system, you can force its 
  installation by using --force. This is NOT RECOMMENDED and may cause the
  stingray traffic manager to become unstable or inoperable.

EOF
   exit;
}

my( $mode, $package, @args ) = @ARGV;

# Validate Parameters
if( ! $mode || ! $package ) {
   die( "Invalid arguments, must supply a mode and package\n" );
}

if(  $mode !~ /^(info|install)$/i ) {
   die( "Invalid mode, must be info or install\n" );
}

if( ! -f $package ) {
   die( "Package '$package' does not exist or is not a file\n" );
} else {
   # Untaint
   $package = $1 if( $package =~ /^(.*)$/ );
}

# Create session for audit log entries and get storage
my $session = createEphemeralSession(
   user => getpwuid( $< ),
   auth => 'console',
);

my $storage = new Zeus::ZXTM::StorageManager();

# Unpack upgrade package and read info
my $rand_dir = int( rand( 999999 ) ) . "-$$";
my( $err, $info, $sub_dir, $info_text ) = UntarPackage( $package, $rand_dir );
if( $err ) {
   die( "Failed to extract upgrade package: $err\n" );
}

my $is_afm = $info->{'internal-is-afm'};

if( $is_afm ) {
   warn <<'HERE';
The Application Firewall cannot be upgraded using this package.

To upgrade the Application Firewall, use the Application Firewall Updater,
accessible from the Application Firewall Administration Server.

HERE
   exit -1;
}

# Print out information if in info mode
if( $mode eq 'info' ) {
   my $formatted = FormatPackageInfo( $info, $sub_dir ); 
   foreach my $key_val ( @$formatted ) {
      print sprintf( "%-15s %s\n", "$key_val->{label}:", $key_val->{value} );
   }

   if( $info->{'internal-restart'} ) {
      print "\nNOTE: The traffic manager will be restarted after installation.\n"
   }
}
print "\n";

# Validate config and print errors
my $errors = ValidatePackage( $info, $sub_dir );
if( keys( %$errors ) ) {
   print( STDERR "This package cannot be installed on this machine:\n" );
   foreach my $error ( keys( %$errors ) ) {
      print( STDERR "   $errors->{$error}\n" );
   }
   if( $mode eq 'install' ) {
      if( ! grep( /^--force$/, @args ) ) {
         exit -1;
      } else {
         print STDERR "\nWARNING: Force is set, the package will be installed anyway\n";
      }
   }
   print "\n";
}


# Work out the information we need from the user
my %INFO_DESC = (
   'cluster-user' => {
      desc =>  "Stingray Cluster Administrator User",
      query => 
         "The system can automatically cluster this Stingray Application Firewall installation with " .
         "the others in this cluster.\n" .
         "Enter the user name to use when clustering (or leave blank to not cluster)",
      optional => 1,
   },
   'cluster-pw' => {
      desc =>  "Stingray Cluster Administrator Password",
      query => "Please enter the password for the cluster user",
      pw => 1,
      optional => 1,
   },

);

my @required_info = ();

if( $mode eq 'info' ) {
   if( @required_info ) {
      print "Required parameters for installation:\n";
      foreach my $req ( @required_info ) {
         my $desc = $INFO_DESC{$req};
         print "   $req - $desc->{desc}\n";
      }
      print "\n";
   }

   exit( keys( %$errors ) ? -1 : 0 ); # Exit if in info mode
}

# Get required info. This comes from 3 sources: the command line arguments, 
# environment variables, and prompt from the user (STDIN)
my %info;
foreach my $arg ( @args ) {
   if( $arg =~ /--([\w-]+)=(.*)/ ) {
      $info{$1} = $2;
   }
}

foreach my $env_var ( keys( %ENV ) ) {
   if( $env_var =~ /^Z_UPGRADE_(.*)/ ) {
      my $key = lc( $1 );
      $key =~ s/_/-/g;
      $info{$key} = $1 if( $ENV{$env_var} =~ /^(.*)$/ );
   }
}

foreach my $info_key ( @required_info ) {
   my $val = $info{$info_key};

   if( ! defined( $val ) ) {
      my $desc = $INFO_DESC{$info_key};

      if( grep( /^--non-interactive$/, @args ) ) {
         die( "Missing required argument '$info_key', and non-interactive set\n" );
      }

      while( 1 ) {
         if( $desc->{pw} ) {
            my $confirm = $desc->{pw_confirm} ? undef : 1;
            $val = Zeus::ZInstall::Common::get_password( 
               $desc->{query}, 
               $confirm
            );
         } else {
            $val = Zeus::ZInstall::Common::get_input( $desc->{query} );
         }

         if( $val eq '' && ! $desc->{optional} ) {
            print( "You must enter a value.\n\n" )
         } else {
            last;
         }
      }
   }

   if( ! defined( $val ) || $val eq '' ) {
      die( "Invalid entry for $info_key\n" );
   }
   $info{$info_key} = $val;
}


# Install the upgrade!
print "Installing $info->{name}...\n";
my( $exitcode, $stdout, $stderr ) = InstallPackage(
   $session, $sub_dir,
   $info->{name} || $sub_dir,
);

my $log = "$stdout\n$stderr";
$log =~ s/^([ \t]*\n)+//g;
$log =~ s/\s+$/\n/;

# Failed to install 
if( $exitcode ) {
   die( "Installation failed.\n\nInstallation Log:\n$log\n" );
}

delete $ENV{'OLDDIR'};

# Perform restart if needed
if( $info->{'internal-restart'} ) {
   print( "Installation successful, restarting the traffic manager...\n" );
} else {
   print( "Installation successful.\n\nInstallation Log:\n$log\n" );
   exit;
}

my( $res_code, $res_out, $res_err ) = RunRestartScript( 
   $sub_dir, $info->{name} || $sub_dir, 
   'NO_FORK' 
);
   
$log .= "\nRestart Log:\n$res_out\n$res_err\n";
$log =~ s/\s+$/\n/;

if( $res_code ) {
   die( "Restart failed.\n\nInstallation Log:\n$log\n" );
}
   
print( "Restart successful.\n\nInstallation Log:\n$log\n" );

