#!/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-2015 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::Execute qw( execute );
use Zeus::ZInstall::ZInstall;
use Zeus::ZXTM::ApplianceUtils qw( reboot_machine );
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 "    --delete                select a version on this partition to delete\n";
      print "    --to=VERSION            change to or delete this specific version\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;
if( !opendir( ZH, '.' ) ) {
   die "Can't read ZEUSHOME: $!";
} else {
   my @zeushome_dir = readdir( ZH );
   closedir( ZH );
   foreach my $dir ( @zeushome_dir ) {
      next if( $dir !~ /^(zxtm|zglb)(admin)?-([0-9].*)$/ );
      if( $2 ) {
         next unless( -d "$dir/docroot" );
         $zxtmadmins{$3} = 1;
      } else {
         next unless( -f "$dir/bin/zeus.zxtm" );
         $zxtms{$3} = 1;
         my @stat = stat( $dir );
         $dates{$3} = $stat[10];
      }
   }
}

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

# Populate list for appliances
my $appliance = 0;
my $no_grub_menu = 0;
my( %grub_index, $old_default, $new_default );
if( -e "/etc/zxtm-version" ) {
   $appliance = 1;

   # Minor versions
   ( 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;
   }

   # Major versions
   if( open( my $grub_fh, "<", "/boot/grub/menu.lst" ) ) {
      my $grub_file = join( "", <$grub_fh> );
      close( $grub_fh );
      my @grub_entries = split( "\n\n", $grub_file );
      my $vm_type = `uname -r`;
      $appliance = "xen" if( $vm_type =~ /xen/ );

      foreach my $entry ( @grub_entries ) {
         if( ( $entry =~ m/title (jetNEXUS Appliance|Stingray Traffic Manager) (\S+) .+savedefault (\d+)/si ) &&
             ( $2 ne $current ) )
         {
            my( $ver, $index ) = ( $2, $3 );
            $grub_index{$ver} = $index;
            push( @matching, $ver );
         } elsif( $appliance eq "xen" ) {
            if( $entry =~ m/default (\d+)/s ) {
               $old_default = $1;
               $new_default = ( $old_default eq 0 ) ? 2 : 0;
            } elsif( ( $entry =~ m/Stingray Traffic Manager (\S+)/s ) &&
                     ( $1 ne $current ) && 
                     ( !exists( $grub_index{$1} ) ) ) {
               $grub_index{$1} = $new_default;
               push( @matching, $1 );
            }
         }
      }
   } else {
      $no_grub_menu = 1;
   }

   @versions = @matching;
}


if( $list ) {
   if( $no_grub_menu ) {
      print "Could not access the grub menu. There may be other versions of the software\n" .
            "on the other partition. If so, refer to the Getting Started Guide for details\n" .
            "on how to downgrade to them. The versions available on this partition are:\n";
   }
   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) 2015, 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 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( scalar( @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
      @versions = grep { $_ ne $current } @versions;
      # or major appliance versions
      @versions = grep { !exists( $grub_index{$_} ) } @versions;
      if( !scalar( @versions ) ) {
         print "You have only one installed version of the software on this partition,\n" .
               "there is no other version to delete.\n";
         exit 0;
      }
   }

   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 );


# Appliance major version rollback
if( $appliance && exists( $grub_index{$toversion} ) ) {
   if( $delete ) {
      print "The version you have specified is on a different partition.\n" .
            "The partition will be erased automatically when required for a\n" .
            "major upgrade.\n\n";
      exit( 0 );
   }
   print "You have selected a major version change. This process will \n" .
         "reboot the appliance and you will be logged out. Do you want\n" .
         "to continue? Y/N [N]:";
   my $confirmation = <STDIN>;
   if( !defined($confirmation) || $confirmation !~ /^y/i ) {
      print "\nRollback aborted.\n\n";
   } else {
      if( $appliance eq "xen" ) {
         if( defined( $old_default ) ) {
            Zeus::ZInstall::Common::rewrite_file( "/boot/grub/menu.lst",
                                                  "default $old_default",
                                                  "default $new_default" );
         } else {
            print "\nRollback unsuccessful: Could not find 'default' line in grub menu\n\n";
            exit( 1 );
         }
      } else {
         my( $exit, $stdout, $stderr ) = execute( [ 'grub-set-default', $grub_index{$toversion} ] );
         if( $exit ) {
            print "\nRollback unsuccessful:\n$stderr\n\n";
            print "Please Refer to the Getting Started Guide for details on how to manually\n" .
                  "attempt an appliance major version rollback.\n\n";
            exit( 1 );
         }
      }
      print "\nRollback successful, rebooting...\n";
      my ( $exit, $stderr ) = reboot_machine();
      if( $exit ) {
         print "\nReboot unsuccessful:\n$stderr\n\n";
      } else {
         print "\nLogging out.\n";
         # Kill the bash process to log the user out
         kill( 'HUP', getppid() );
      }
   }
   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",
               "stingrayafm-$toversion", "updater-$toversion",
               "/logs/stingrayafm/stingrayafm-$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 );

   # If the existing version has a rollback helper, run it.
   if( -e "./zxtm/bin/rollback-helper" ) {
      print "Running pre version change hook...\n";
      system( "./zxtm/bin/rollback-helper --hook=pre --from=$current --to=$toversion" );
   }

   # Remove symlinks for each product we're rolling back
   foreach my $product( qw( zxtm zxtmadmin stingrayafm updater ) ) {
      if( -l $product ) {
         unlink( $product ) or die "Cannot remove $product 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";
   }

   my $ver_fh;
   if( -e "/etc/zxtm-version" && open( $ver_fh, "<", "/etc/zxtm-version" ) ) {
      # Update the zxtm-version file to the correct version. The newer patch
      # level can remain as all other packages are still at this level
      my $version_text = join( "", <$ver_fh> );
      close( $ver_fh );
      if( ( $version_text =~ /\nPRODUCT_VERSION=(\d+\.\w+)\n/s ) &&
          ( open( $ver_fh, ">", "/etc/zxtm-version" ) ) ) {
         $version_text =~ s/\nPRODUCT_VERSION=$1\n/\nPRODUCT_VERSION=$toversion\n/s;
         print( $ver_fh $version_text );
         close( $ver_fh );
         # Update the grub menu with the new version
         system( "/usr/sbin/update-grub" );
      }
   }

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

   # The firewall and updater directories might not exist in a previous installation
   if( -e "stingrayafm-$toversion" ) {
      if( -d "zeusafm" && !-l "zeusafm" && !-e "stingrayafm-$current" ) {
         # Might be rolling forward after previously rolling back and installing SAF
         rename( "zeusafm", "stingrayafm-$current" );
         symlink( "stingrayafm", "zeusafm" );
      }
      symlink( "stingrayafm-$toversion", "stingrayafm" ) or die "Cannot create stingrayafm symlink: $!\n";
   }
   if( -e "updater-$toversion" ) {
      if( -d "updater" && !-l "updater" && !-e "updater-$current" ) {
         # Might be rolling forward after previously rolling back and installing SAF
         rename( "updater", "updater-$current" );
      }
      symlink( "updater-$toversion", "updater" ) or die "Cannot create updater symlink: $!\n";
   }

   print "Updating $toversion rollback tool to latest version...\n";
   Zeus::ZInstall::Common::copy_file( "zxtm-$current/bin/rollback", "zxtm-$toversion/bin/rollback" );

   # If the target version has a rollback helper, run it.
   if( -e "./zxtm/bin/rollback-helper" ) {
      print "Running post version change hook...\n";
      system( "./zxtm/bin/rollback-helper --hook=post --from=$current --to=$toversion" );
   }

   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 );
   if( $appliance ) {
      # Update the appliance boot screen
      system( "pkill z-doneboot" );
   }
}

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