#!/bin/sh
# -*- perl -*-
# vim:set syn=perl:
#
# (c) Copyright 1999-2013, Riverbed Technology, Inc. All rights reserved.
#
# DISCLAIMER NOTICE
#
# This source code ( the Software ) is the copyrighted work of Zeus
# Technology Limited ( Zeus ) and is governed by and subject to licence.
# The Software is made available for use only in accordance with the
# terms of such licence. Any reproduction or redistribution of the
# Software not in accordance with the licence is expressly prohibited by
# law, and may result in severe civil and criminal penalties.
#
# WITHOUT LIMITING THE FOREGOING, ANY MODIFICATION OF THE SOFTWARE OR
# COPYING OR REPRODUCTION OF THE SOFTWARE TO ANY OTHER MEDIUM OR
# LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY
# PROHIBITED.
#
# THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF
# THE LICENCE. EXCEPT AS WARRANTED IN THE LICENCE, ZEUS HEREBY DISCLAIMS
# ALL WARRANTIES AND CONDITIONS WITH REGARD TO THE SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
# IN NO EVENT SHALL ZEUS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THE SOFTWARE.
#
# ----------------------------------------------------------
# zxtm/configure

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 $LONGNAME installation"
  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::ZInstall::Common;
use Zeus::ZInstall::Cluster;
use Zeus::ZXTM::Configure;
use Zeus::ZXTM::Utils qw( GetServerName );
use Zeus::Execute qw( execute );
use Zeus::NetworkingUtils qw( isResolvableHostname );

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 $nostart    = 0;
my $recordfile = undef;
my $replayfile = undef;
my $alreadyacceptedlicence = 0;

foreach ( @ARGV ) {
   if ( /^-h|-\?|--help$/ ) {
      usage();
      print "Options:\n";
      print "    --help                  this message\n";
      print "    --nostart               don't call start-zeus after configure\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 'nostart' )            { $nostart = 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 'acceptedlicenseviainstall' ) { $alreadyacceptedlicence = 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::Configure::ReadBranding();
my $LONGNAME  = Zeus::ZXTM::Configure::GetLongName();

print <<EOM;
Riverbed Configuration Program
Copyright (C) 2013, Riverbed Technology, Inc. All rights reserved.

EOM

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 ( $::noninteractive && ! defined $replayfile ) {
   Zeus::ZInstall::Common::fatal( "A replay file must be specified to use --noninteractive\n" );
}

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( "$LONGNAME not installed (missing zxtm directory)" )
  unless defined( $installuid );
if( $installuid != $> ) {
   my $iuser = (getpwuid $installuid )[0] || $installuid;
   my $user  = (getpwuid $>)[0] || $>;
   print "WARNING: $LONGNAME was installed as user '$iuser', but you are user '$user'.\n\n";
   if( $user eq "root" ){
   print <<EOF;
You are about to configure $LONGNAME as a different user to the user who performed
the installation. This may result in the original user not being able to
reconfigure this $LONGNAME.

EOF
   } else {
   print <<EOF;
You are about to configure $LONGNAME as a different user to the user who performed
the installation. You may not have permission to complete the configuration and
it may result in the original user not being able to reconfigure this $LONGNAME.

EOF

   }
   my $choice;
   while( !defined $choice ) {
      $choice = Zeus::ZInstall::Common::get_input( "Do you want 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 );
      }
   }
}

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

# Have we already been configured?
my $is_reconfigure = Zeus::ZXTM::Configure::HaveRcSymlinks();

if ( ! $is_reconfigure ) {
   Zeus::ZInstall::Common::show_license() unless $alreadyacceptedlicence;

} else {
   print <<EOF;
Initial configuration has already been performed on this Stingray Traffic
Manager installation.

1. Quit (default)
2. Perform the post-install configuration again
3. Clear all configuration
H. Help

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

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

This $LONGNAME installation is already configured and the administration
server interface can be used for configuring the traffic management.

You may choose to perform the initial configuration again, which will
allow you to change settings such as whether the installation starts up
at boot time. If you choose to perform the configuration again, the
default answers to all questions will be the answers provided previously.

Alternatively you can choose to remove all the configuration from this
$LONGNAME installation. This will stop $LONGNAME from handling traffic, so
you should ensure that this will not affect your external availability.

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 clear all configuration for $LONGNAME install in
$ENV{ZEUSHOME}.  This will stop $LONGNAME from managing any traffic.
You should ensure that this will not affect any traffic before
continuing.

EOF

      my $value = Zeus::ZInstall::Common::get_input(
                  "Enter 'yes' if you wish to clear the configuration",
                   undef, undef, 'zxtm!really_clear_config' );
      Zeus::ZInstall::Common::fatal( "Configuration aborted, configuration unchanged\n" )
              if $value !~ /^yes$/i;

      Zeus::ZXTM::Configure::StopSoftware();
      Zeus::ZXTM::Configure::RemoveFromCluster();

      print "Resetting configuration...";
      Zeus::ZXTM::Configure::ResetZXTMConfig();
      print "OK\n";

      print <<EOF;

The configuration for this $LONGNAME machine has now been cleared. It
is no longer part of a cluster, and won\'t be usable until this
configuration program is re-run to perform the initial configuration
again.

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 reconfiguration
}

# Ensure global.cfg symlink is correct - hostname may have changed
Zeus::ZXTM::Configure::FixGlobalCfg();

# Create a Control SSL certificate if necessary
print "Generating SSL key for control communications... " unless( $main::quiet );
my $cfp = Zeus::ZXTM::Configure::InstallControlSSLKey();
print "done\nControl SSL fingerprint: $cfp\n\n" unless( $main::quiet );

# Licence Key
Zeus::ZXTM::Configure::InstallLicenceKey();

# User and groups
Zeus::ZXTM::Configure::ConfigureUserGroup();

# Management IP
Zeus::ZXTM::Configure::ConfigureManagementIP();

# Check to see if TM name is resolvable
my $tmname = GetServerName();
if( !isResolvableHostname( $tmname ) ) {
   my $nameip = Zeus::ZXTM::Configure::ConfigureTrafficManagerName();

   if( $nameip ) {
      Zeus::ZXTM::Configure::FixGlobalCfg( $nameip );
   }
}

# Ports
my ( $commport, $adminport, $appletport ) =
    Zeus::ZXTM::Configure::ConfigurePorts();

# Create an SSL certificate if necessary
my $afp = "";
if( ! ( grep /^security\!enabled\s+[Yy]es$/, Zeus::ZInstall::Common::read_file( "$ENV{ZEUSHOME}/admin/website" ) ) ) {
   print "Installing SSL key for Admin Server... " unless( $main::quiet );
   $afp = Zeus::ZXTM::Configure::InstallAdminSSLKey();
   Zeus::ZXTM::Configure::StopAdminServer( 1 );
   print "done\n" unless( $main::quiet );
} else {
   $afp = Zeus::ZXTM::Configure::GetAdminSSLCertFingerprint();
}

# Register with other admin servers, and setup admin password
Zeus::ZXTM::Configure::RegisterZXTM( $commport );

# Set up AFM gui redirection as needed
Zeus::ZXTM::Configure::FixAFMRedirection();

# Test the network configuration and detect possible failures
Zeus::ZXTM::Configure::TestNetwork();

# Should the product be bootable?
Zeus::ZXTM::Configure::choose_bootable();

# Update the permissions for the conf directory, so that
# only the user running this program can write to them
Zeus::ZXTM::Configure::UpdateConfPerms();

# Make the symlinks for zxtm and zxtmadmin, this is last so
# that the default ./start-zeus program won't work
# until this step is done
Zeus::ZXTM::Configure::CreateRcSymlinks();

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


if ( ! $nostart ) {
   # Start ZXTM
   Zeus::ZXTM::Configure::StartSoftware( "" );

   # Display end message
   chomp( my $hostname = `hostname` );
   my $domain = Zeus::ZInstall::Common::domainname( $hostname );

   my $tm_name = GetServerName() || "${hostname}${domain}";
   
   print <<EOF;

**
** The SHA-1 fingerprint of the admin server's SSL certificate:
**   $afp
** Keep a record of this for security verification when connecting
** to the admin server with a web browser and when clustering other
** $LONGNAME installations with this one.
**
** To configure the $LONGNAME, connect to the admin server at:
**   https://${tm_name}:${adminport}/
** and login as 'admin' with your admin password.
**

EOF
   if( !$main::quiet && -f "$ENV{ZEUSHOME}/zxtm/RELEASE_NOTES" ) {
      print <<EOF;
Please read the release notes ($ENV{ZEUSHOME}/zxtm/RELEASE_NOTES)

EOF
   }
}

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