#!/bin/sh
# -*- perl -*-
# vim:set syn=perl:
#
# (c) Copyright 1999-2015, Riverbed Technology, Inc. All rights reserved.
#
# ----------------------------------------------------------
# zxtm/setupafm

ZCWD=`pwd`
export ZCWD

OLD_ZEUSHOME=$ZEUSHOME

# Use the directory we are installed in in preference to the ZEUSHOME
# set in the env variable. We fall back to that variable

# Have a good guess, we live in $ZEUSHOME/zxtm
OLD_PWD=`pwd`
cd `dirname $0`/..
ZEUSHOME=`pwd`
cd $OLD_PWD

# Try the old ZEUSHOME if we failed to find one ourselves
if [ ! -d "$ZEUSHOME/zxtm" ]
then
    ZEUSHOME=$OLD_ZEUSHOME
    export ZEUSHOME
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
  echo 'FATAL: $ZEUSHOME is not set, or is set incorrectly'
  echo 'It should point to the Stingray software installation running the traffic manager'
  exit 1
fi

export ZEUSHOME
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}
#----------------------------------------------------------`"
#!perl -w
#line 69

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

use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::AFMConfigure;
use Zeus::Execute qw( execute );
use strict;
$| = 1;

# If the installation fails in some way, then reporting English error
# messages to our support staff ensures a faster response to customers.
$ENV{LANG}   = 'C';
$ENV{LC_ALL} = 'C';

# Something sensible
umask 022;

# ============================================================
# Setup the variables that the ZInstall Perl Modules need
# ============================================================
$::instdir    = undef;      # The directory that the install stuff is in
$::initialdir = $ENV{ZCWD}; # Our initial directory that we were called from
$::toolsdir   = "$ENV{ZEUSHOME}/zxtm/bin"; # The Location of the install tools
Zeus::ZInstall::Common::set_product_name( 'zxtm' );

chdir $ENV{ZEUSHOME};

sub usage {
   print STDERR @_ if @_;
   print STDERR "Usage: configure [options]\n";
}

# ----------------------------------------------------------
# Process arguments
$::noninteractive = 0;
$::verbose = 0;
$::noloop  = 0;
$::quiet = undef;
my $upgrade    = 0;
my $nostart    = 0;
my $recordfile = undef;
my $replayfile = undef;
my $alreadyacceptedlicence = 0;
my $username = undef;

foreach ( @ARGV ) {
   if ( /^-h|-\?|--help$/ ) {
      usage();
      print "Options:\n";
      print "    --username              If a cluster can be joined, use this username\n";
      print "    --upgrade               Upgrade existing installation preserving configuration\n";
      print "\n";
      print "    --help                  this message\n";
      print "    --noloop                exit if answer is invalid\n";
      print "\n";
      print "    --record-to=FILE        Save the install answers to the specified file\n";
      print "    --replay-from=FILE      Use the answers specified in the file\n";
      print "    --noninteractive        abort if an answer is not specified in the replay file\n";
      print "    --quiet                 Hide some of the install text\n";
      print "\n";
      exit 0;

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

      # Check valid options and set variables
      if ( $key eq 'verbose' )               { $::verbose = 1; }
      elsif ( $key eq 'noloop' )             { $::noloop = 1; }
      elsif ( $key eq 'quiet' )              { $::quiet = 1; }

      elsif ( $key eq 'record-to' )          { $recordfile = $val; }
      elsif ( $key eq 'replay-from' )        { $replayfile = $val; }
      elsif ( $key eq 'noninteractive' )     { $::noninteractive = 1; }
      elsif ( $key eq 'username' )           { $username = $val; }
      elsif ( $key eq 'upgrade' )            { $upgrade = 1; }
      else {
         print "Unknown option: $_\n";
         exit 1;
      }
   } else {
      usage( "Unhandled parameter: $_\n" );
      exit 1;
   }

   # Force noloop if input is not a tty
   if ( ! -t STDIN ) {
      $::noloop = 1;
   }
}

# ----------------------------------------------------------
# Main code

Zeus::ZXTM::AFMConfigure::ReadBranding();
my $SHORTNAME = Zeus::ZXTM::AFMConfigure::GetShortName();
my $LONGNAME  = Zeus::ZXTM::AFMConfigure::GetLongName();

if ( defined $replayfile ) {
   $replayfile = Zeus::ZInstall::Common::normalize_filename( $replayfile );
   Zeus::ZInstall::Common::fatal( "Replay file does not exist\n" ) unless -e $replayfile;
   Zeus::ZInstall::Common::fatal( "Replay file is not a file\n" ) unless -f $replayfile;
   Zeus::ZInstall::Common::load_answers( $replayfile );
}

if( !$::quiet ) {
   print "This program will perform the initial configuration of the\n";
   print "$LONGNAME.\n\n";
}

# Check we are being (effectively) ran as the user who previously
# installed the product...
my $installuid = (stat "zxtm")[4];
Zeus::ZInstall::Common::fatal( "$SHORTNAME not installed (missing zxtm directory)\n" )
  unless defined( $installuid );


# ============================================================
# This is the start of the main program
# ============================================================

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

# Have we already been configured?
my $reconfigure = Zeus::ZXTM::AFMConfigure::AlreadyConfigured();

if( $reconfigure && ! $::noninteractive ) {
   print <<EOF;
Initial configuration has already been performed on this
$LONGNAME installation.

1. Quit (default)
2. Reinstall $SHORTNAME
3. Remove $SHORTNAME from the Zeus Traffic Manager
H. Help

EOF
   my $choice;
   while ( ! defined $choice ) {
      $choice = Zeus::ZInstall::Common::get_input('Choose option',
                           '1', '[Hh123]', 'afm!configure_option' );

      if ( $choice =~ /h/i ) {
         print <<EOF;

The $LONGNAME is already installed. You can access
$SHORTNAME Administration Server from the System -> Application Firewall
page of the Stingray Traffic Manager Administration Server.

You can choose to perform the initial configuration again, which will
reset the link between the Stingray Traffic Manager and $SHORTNAME to
its default state. Note that this will not affect the $SHORTNAME configuration
itself.

Alternatively you can choose to decouple the $LONGNAME
from the Zeus Traffic Manager entirely. If you do this, none of your traffic
will be scanned by $SHORTNAME but $SHORTNAME will remain on the system with
its current configuration. You can use $SHORTNAME again by running
this configuration program.

Choosing the default option to quit will leave all configuration unchanged.

EOF
         $choice = undef;
      }
   }

   if ( $choice eq '1' ) {

      print "You have chosen to quit. The configuration is unchanged.\n\n";
      exit(0);

   } elsif ( $choice eq '3' ) {

      print <<EOF;
This option will cause all traffic to pass through the Zeus Traffic Manager
without being scanned by $SHORTNAME.
The $SHORTNAME configuration will remain unchanged should you choose to reinstall
it.

EOF

      my $value = Zeus::ZInstall::Common::get_input(
                  "Enter 'yes' if you wish to uninstall $SHORTNAME",
                   undef, undef, 'afm!really_uninstall' );
      Zeus::ZInstall::Common::fatal( "Installation aborted, configuration unchanged\n" )
              if $value !~ /^yes$/i;

      # Uninstall the AFM...
      Zeus::ZXTM::AFMConfigure::UninstallAFM( $storage );
      print "OK\n";

      print <<EOF;

The $LONGNAME has been uninstalled.
Run this program again if you want to reinstall $SHORTNAME.

EOF
      if ( defined $recordfile ) {
         $recordfile = Zeus::ZInstall::Common::normalize_filename( $recordfile );
         Zeus::ZInstall::Common::save_answers( $recordfile );
      }
      exit(0);
   }
   # Fall through, the code below handles the (re)installation
}

my $errs = Zeus::ZXTM::AFMConfigure::ConfigureAFM( storage => $storage,
                                                   username => $username,
                                                   password => $ENV{'ZEUS_AFM_NEW_PASSWORD'},
                                                   upgrade => $upgrade );

if( $errs ) {
   Zeus::ZInstall::Common::fatal( "Configuration failed:\n$errs\n" );
   exit( 1 );
}

print " \nConfiguration successful\n" unless( $main::quiet );


# Now we are successful at configuring ZXTM, save the results of the
# questions
if ( defined $recordfile ) {
   $recordfile = Zeus::ZInstall::Common::normalize_filename( $recordfile );
   Zeus::ZInstall::Common::save_answers( $recordfile );
}
exit(0);
