#!/bin/sh
#
# Switch to a different version of Zeus Traffic Manager

# 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 ..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "rollback FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get networking commands into our PATH
PATH=/sbin:/usr/etc/sbin:/usr/etc:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#!perl -w
#line 31

=head1 NAME

rollback - change to a different installed version of Zeus Traffic Manager

=head1 SYNOPSIS

B<rollback>

=head1 DESCRIPTION

B<rollback> can be used interactively to select a different version of
the software to use. This can be useful if you would like to roll back
to an earlier installed version of the software. Note that changing
the running version does not preserve current configuration settings -
the old version selected will have the last configuration that it
originally used.

=head1 COPYRIGHT

Copyright (C) 2000-2013 Zeus Technology Limited. All rights reserved.

=cut

# NB this code is designed to be very simple and not have many library
# dependencies. This is so that it can be easily installed in older versions
# of ZXTM (and so allow the user to roll forwards as well).


# setup our libraries
BEGIN {
   unshift @INC, ( "$ENV{ZEUSHOME}/perl",
                   "$ENV{ZEUSHOME}/admin/lib/perl",
                   "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
                   "$ENV{ZEUSHOME}/zxtm/lib/perl",
                 );
}

use Zeus::KeyValueConfigFile;
use Zeus::ZInstall::ZInstall;
use strict;



chdir( $ENV{ZEUSHOME} ) or die "Can't cd to $ENV{ZEUSHOME}: $!\n";

# ----------------------------------------------------------
# Process arguments
my $toversion;
my $list = 0;
my $delete = 0;

foreach ( @ARGV ) {
   if( /^-h|-\?|--help$/ ) {
      print "Usage: rollback [options]\n";
      print "Options:\n";
      print "    --help                  this message\n";
      print "    --list                  show available software versions\n";
      print "    --to=VERSION            change to or delete this specific version\n";
      print "    --delete                select a version to delete\n";
      print "\n";
      exit 0;

   } elsif ( /^--(.*?)=(.*)$/ || /^--(.*)$/ ) {
      my( $key, $val ) = ( $1, $2 );

      # Check valid options and set variables
      if( $key eq 'to' ) { $toversion = $val; }
      elsif( $key eq 'list' ) { $list = 1; }
      elsif( $key eq 'delete' ) { $delete = 1; }
      else {
         print STDERR "Unknown option: $_\n";
         exit 1;
      }
   } else {
      print STDERR "Unknown parameter: $_\n";
      exit 1;
   }
}

my %zxtmadmins;
my %zxtms;
my %dates;
opendir( ZH, '.' ) or die "Can't read ZEUSHOME: $!";
foreach( readdir( ZH )) {
   next unless( /^(zxtm|zglb)(admin)?-([0-9].*)$/ );
   if( $2 ) {
      next unless( -d "$_/docroot" );
      $zxtmadmins{$3} = 1;
   } else {
      next unless( -f "$_/bin/zeus.zxtm" );
      $zxtms{$3} = 1;
      my @stat = stat;
      $dates{$3} = $stat[10];
   }
}
closedir( ZH );

# Only list installs of both zxtm and the zxtmadmin package
my @versions;
foreach ( keys %zxtms ) {
   push( @versions, $_ ) if( $zxtmadmins{$_} );
}

@versions = sort { $dates{$a} <=> $dates{$b} } @versions;

# Get current running version of ZXTM
my $current = readlink( 'zxtm' );
if( $current ) {
   $current =~ s/^.*-([0-9].*)$/$1/;
} else {
   # Don't exit here, let customer pick a working ZXTM to fix problem.
   warn "Cannot read existing zxtm symlink - current version is unknown\n";
   $current = 'mystery';
}

# The ZXTM Appliance should not offer major version downgrades
my $appliance = 0;
if( !$delete && -e "/etc/zxtm-version" ) {
   $appliance = 1;
   ( my $majorver = $current ) =~ s/^([\d.]+).*$/$1/;
   my @matching = ();
   foreach my $ver ( @versions ) {
      ( my $mver = $ver ) =~ s/^([\d.]+).*$/$1/;
      push @matching, $ver if $majorver eq $mver;
   }
   @versions = @matching;
}


if( $list ) {
   print "@versions\n";
   exit 0;
}

my $action = "use";
if( $delete ) {
   $action = "delete";
}

# We must be root, or the ZXTM install user
if( $< ) {
   my @stat = stat( 'zxtm' );
   die "Cannot stat zxtm symlink: $!\n" unless( @stat );
   if( $stat[4] != $< ) {
      die "You must run this program as root, or as the user who originally installed the software\n";
   }
}

if( !$toversion ) {
   # Interactively select version to use/delete
   print "\nRollback\nCopyright (C) 2013, Riverbed Technology, Inc. All rights reserved.\n\n";

   print "This program allows you to roll back to a previously\n"
       . "installed version of the software. Please note that the older version\n"
       . "will not gain any of the configuration changes made since upgrading.\n\n";

   print "To downgrade between major versions please refer to the\n"
       . "Getting Started Guide.\n\n" if $appliance;

   print "To delete obsolete versions of the software, use the --delete option\n\n";

   print "Deletion of obsolete versions is permanent, it is highly\n",
       "recommended to take backups before deleting old installations\n\n"
           if $delete;

   if( -e "$ENV{ZEUSHOME}/zxtmafm" ) {
      print "This program does not affect the Stingray Application Firewall,\n"
          . "but your traffic manager may stop using it, depending on your\n"
          . "old configuration. See the Stingray Application Firewall manual\n"
          . "for how to roll back the Stingray Application Firewall.\n\n"
   }

   if( @versions == 1 ) {
      print "You have only one installed version of the software, there is no\n"
        . "other version to ${action}.\n";
      exit 0;
   }

   if( $delete ) { # don't delete current version, please
      @versions = grep { $_ ne $current } @versions;
   }

   my $choice;
   while( !defined $choice ) {
      $choice = Zeus::ZInstall::Common::get_input( "Do you want to continue? Y/N",
                                                   "N", "[yn]", 'zxtm!wrong_user' );
      if( $choice =~ /n/i ) {
         print "You have chosen to quit.  The configuration is unchanged.\n\n";
         exit( 0 );
      }
   }

   print "\nWhich version of the software would you like to ${action}?\n";
   my $num = 0;
   my $default = '';
   my $options = '';
   foreach my $version ( @versions ) {
      $num++;
      my $extra = '';
      if( $delete ) {
         if( !length( $default ) ) { # default to oldest for deletion
            $default = $num;
         }
      } else {
         if( $version eq $current ) {
            $default = $num;
            $extra = '(current version)';
         }
      }
      print "  $num) $version $extra\n";
      if( length( $options ) ) {
         $options .= "|$num";
      } else {
         $options = $num;
      }
   }

   if( $delete ) {
      $num++;
      print "  $num) Abort (do nothing)\n";
      $options .= "|$num";
   }
   my $pick = Zeus::ZInstall::Common::get_input( "Select a version", $default,
                                                 "($options)", 'zxtm!rb_version' );

   $toversion = $versions[$pick - 1];
   if( ! defined( $toversion ) ) {
      print "No action taken.\n";
      exit( 0 );
   }


   if( $toversion eq $current ) {
      print "Leaving current version unchanged.\n\n";
      exit( 0 );
   }
}

die "You are currently running version $current\n" if ( $current eq $toversion );

# Check AFM version compatiblity
if( -e "$ENV{ZEUSHOME}/zeusafm" && ! $delete ) {
   my $afm_version = readlink( "$ENV{ZEUSHOME}/zeusafm/current" );

   if( $afm_version =~ /zeusafm\/(\d+\.\d+)/ ) {
      $afm_version = $1;
   }
   
   if( $toversion =~ /^(\d+)\.(\d+)/ ) {
      my( $to_major, $to_minor ) = ( $1, $2 );
      if( $to_major < 8 && $afm_version !~ /^[123]\./ ) {
         print 
            "WARNING: Traffic manager version $toversion is incomatable with the\n" .
            "         installed Application Firewall version $afm_version. You\n" .
            "         will have to perform a manual rollback to version 3.5 or\n" .
            "         earlier.\n\n" .
            "Please confirm Y/N [N]: ";

         my $confirmation = <STDIN>;
         if( !defined($confirmation) || $confirmation !~ /^y/i ) {
            print "Not confirmed - no action taken.\n";
            exit( 0 );
         }
      }
   }
}

my $link_target = ( -e "zglb" ) ? "zglb-$toversion" : "zxtm-$toversion";
die "Directory $link_target does not exist\n" if ( ! -d $link_target );
die "Directory zxtmadmin-$toversion does not exist\n" if ( ! -d "zxtmadmin-$toversion" );

# Versions before 5.0 had a different admin version from the main product
my %adminversions = (
                     "2.0"   => "4.3b1",
                     "2.0r1" => "4.3b1",
                     "3.0"   => "4.3",
                     "3.1"   => "4.4a2",
                     "3.1r1" => "4.4a3",
                     "3.2"   => "4.4b1",
                     "4.0"   => "4.4a7",
                     "4.0r1" => "4.4a9",
                     "4.0r2" => "4.4a10",
                     "4.0r3" => "4.4a11",
                     "4.1"   => "4.4a15",
                     "4.1r1" => "4.4a16",
                     "4.1r2" => "4.4a16",
                     "4.1r3" => "4.4a17",
                     "4.2"   => "4.4a21",
                     "4.2r1" => "4.4a22",
                     "4.2r2" => "4.4a23",
                    );
my $admintoversion = exists $adminversions{$toversion} ? 
                         $adminversions{$toversion} : $toversion;
my $rollbackadmin = -e "admin-$admintoversion" ? 1 : 0;

if( $delete ) {

   print "WARNING: About to remove version '$toversion'.\n",
       "Please confirm Y/N [N]:\n";
   my $confirmation = <STDIN>;
   if( !defined($confirmation) || $confirmation !~ /^y/i ) {
      print "Not confirmed - no action taken.\n";
      exit( 0 );
   }

   for my $d ( "zxtm-$toversion", "admin-$admintoversion", "zxtmadmin-$toversion" ) {

      if( -d $d  ) {
         print "Removing $d...\n";
         if( system( "rm -rf \Q$d\E" ) ) {
            die "Failed to remove $d directory: $!\n";
         }
         print " ... done\n";
      }
   }
} else {

   print "\nStopping existing version ...\n";

   system( "./stop-zeus" );
   die "stop-zeus failed: $!\n" if( $? == -1 );
   die "stop-zeus died with signal " . ( $? & 128 ) . "\n" if( $? & 127 );
   die "stop-zeus failed\n" if( $? >> 8 );

   unlink( "zxtm" ) or die "Cannot remove zxtm symlink: $!\n";
   unlink( "zxtmadmin" ) or die "Cannot remove zxtmadmin symlink: $!\n";
   if( $rollbackadmin ) {
      unlink "admin" or die "Cannot remove admin symlink: $!\n";
   }

   print "\nChanging to version $toversion...\n";

   symlink( "zxtmadmin-$toversion", "zxtmadmin" ) or die "Cannot create zxtmadmin symlink: $!\n";
   if( $rollbackadmin ) {
      symlink( "admin-$admintoversion", "admin" ) or die "Cannot create admin symlink: $!\n";
   }

   if( -e "zglb" ) {
      unlink( "zglb" ) or die "Cannot remove zglb symlink: $!\n";
      symlink( $link_target, "zglb" ) or die "Cannot create zglb symlink: $!\n";
      symlink( $link_target, "zxtm" ) or die "Cannot create zxtm symlink: $!\n";
   } else {
      symlink( $link_target, "zxtm" ) or die "Cannot create zxtm symlink: $!\n";
   }

   print "\nStarting alternate version...\n";

   system( "./start-zeus" );
   die "start-zeus failed: $!\n" if( $? == -1 );
   die "start-zeus died with signal " . ( $? & 128 ) . "\n" if( $? & 127 );
   die "start-zeus failed\n" if( $? >> 8 );
}

print "\nFinished.\n";
if( !$delete ) {
   print "Remember, you can use this tool to undo this change.\n";
}
exit 0;
