#!/bin/sh
#
# CLI for ZXTM

# Check for stand-alone version (overrides any ZEUSHOME)
if [ -d "`dirname $0`/resources" ]; then
   ZEUSHOME=`dirname $0`/resources/
   export ZEUSHOME
fi

# 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
    else
       echo "Broken installation: missing components."
       exit 1
    fi
fi

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

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

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

use strict;
use Zeus::ZXTM::CLI::CLI;
use Zeus::ZXTM::CLI::IO qw( parseArguments formatJSON formatDisplay
                            formatWrapped initTerminal getTerminalWidth
                            disableTerminal );
use Zeus::ZXTM::CLI::AutoComplete qw( autoComplete expandWildcards
                                      expandMethods );
use Zeus::Dumper;
use Term::ReadLine;
use Zeus::MD5 qw( md5 );
use Zeus::Debug;
use Zeus::ZXTM::DeveloperEdition qw( isDeveloperEditionKey DeveloperEditionBanner );

my( $host, $port, $passwd, $debug, $term, $verbose, $script, $continue,
    $attribs, $separator, $wsdldir, $histfile );
my $interactive = -t STDIN;
my $formatoutput = undef;
my $user; 
my $use_commkey = 0;
my $commkeytime;
my $version = 1;
my $timeout = 100;
my $ssl = 1;
my $standalone = ( ! -e "$ENV{ZEUSHOME}/zxtm/bin/zeus.zxtm" );


$| = 1;

# Write into $0 to 'hide' the fact we are perl (this is NOT a no-op)
$0 = "$0";

# Save the command-line history
sub saveHistory
{
   if( $histfile ) {
      my $umask = umask( 0077 );
      my @list = @readline::rl_History;
      if( @list && open( HISTORY, ">$histfile" )) {
         print HISTORY join( "\n", @readline::rl_History ), "\n";
         close( HISTORY );
      }
      umask( $umask );
   }
}


END {
   saveHistory();
}


# Command-line help
sub usage(;$)
{
   my( $fh ) = @_;
   $fh = *STDOUT unless defined $fh;

   print $fh $standalone ? "Usage: $0 [OPTIONS] [user\@]host:port [script file]\n"
                     : "Usage: $0 [OPTIONS] [user\@][host:port] [script file]\n";
   print $fh <<EOF;
Configure Stingray Traffic Manager from a script file or standard input.

  --user USER        Set the username (default: admin)
  --passfile FILE    Read the password from this file
  --nossl            Your traffic manager does not have SSL enabled admin server
  --verbose          Verbose output (for testing)
  --continue         When running a script, continue even if an error occurs
  --help             Show this help
  --version          Show the version of this program
  --formatoutput     Use 'human readable' output, even in script mode
  --json             Use strict JSON output, even in interactive mode
  --timeout SECONDS  Set timeout for commands

EOF
   if( !$standalone ) {
      print $fh "If no host:port is specified, the local traffic manager will be used.\n\n";
   }
}

sub dieWithUsage($)
{
   my( $msg ) = @_;

   $msg .= "\n" unless $msg =~ /\n/s;
   print STDERR "ERROR: $msg";
   print STDERR "\n";
   usage( *STDERR );

   exit 1;
}


# Report an error. If running interactively, or with the continue-on-error
# option, execution of further commands can continue. Otherwise, we exit
sub reportError($)
{
   my $err = shift;
   chomp( $err );
   chomp( $err );
   warn formatWrapped( $err );
   exit 1 if( !$interactive && !$continue );
}


##############################################################################

D( 1, "ZCLI Starting" );

while( @ARGV ) {
   $_ = shift( @ARGV );
   if( /^--/ ) {
      if( /^--debug$/ ) {
         $debug = 1;
      } elsif( /^--passfile$/ ) {
         my $passwdfile = shift;
         dieWithUsage( "Missing password file after --passfile\n" ) unless defined $passwdfile;

         open( PASSWD, $passwdfile ) or dieWithUsage "Cannot read password file: $!\n";
         $passwd = <PASSWD>;
         close( PASSWD );
         $passwd = '' if( !defined( $passwd ));
         chomp( $passwd );
         dieWithUsage "Empty password file\n" if( $passwd eq '' );
      } elsif( /^--user$/ ) {
         $user = shift;
         dieWithUsage( "Missing username after --user\n" ) unless defined $user;
      } elsif( /^--nossl$/ ) {
         $ssl = 0;
      } elsif( /^--formatoutput$/ ) {
         $formatoutput = 1;
      } elsif( /^(-v|--verbose)$/ ) {
         $verbose = 1;
      } elsif( /^--continue$/ ) {
         $continue = 1;
      } elsif( /^(-j|--json)$/ ) {
         $formatoutput = 0;
      } elsif( /^(-h|--help)$/ ) {
         usage();
         exit 0;
      } elsif( /^--wsdldir$/ ) {
         # Local cache location for WSDL files (Only for debugging)
         $wsdldir = shift;
      } elsif( /^--separator$/ ) {
         # Prints a separator after the end of all output, useful for
         # testing
         $separator = 1;
      } elsif( /^--timeout$/ ) {
         $timeout = shift;
      } elsif( /^--version$/ ) {
         print "Version $version\n";
         exit;
      } else {
         dieWithUsage( "Unknown argument '$_'\n" );
      }
   } elsif( /^(\S+?):(\d+)$/ ) {
      if( defined( $host )) {
         dieWithUsage( "Only one traffic manager can be specified on the command line\n" );
      } else {
         ( $host, $port ) = ( $1, $2 );
         $user = $1 if( $host =~ s/^(.*?)\@// );
      }
   } else {
      if( defined( $script )) {
         dieWithUsage( "Only one script can be specified on the command line\n" );
      } else {
         $script = $_;
         $interactive = 0;
      }
   }
}


my $commfile = "$ENV{ZEUSHOME}/zxtm/conf/commkey";
my $commkey_user = "!!ZCLI!!";

# Only use the commkey if the user hasn't defined a username, password or host
$use_commkey = !defined( $user ) && !defined( $passwd ) && !defined( $host ) && -r $commfile;

my @stat = stat( $commfile );

if( $use_commkey ) {
   local *COMM;
   if( open( COMM, "< $commfile" )) {
      $user = $commkey_user;
      $passwd = <COMM>;
      chomp( $passwd );
      $passwd = lc ( md5( $passwd ) );
      close( COMM );
      $commkeytime = $stat[9];
   }
}

if ( !defined( $user ) ) { 
   $user = 'admin';
}

$formatoutput = $interactive if( !defined( $formatoutput ));
initTerminal() if( $interactive );

my $cli = new Zeus::ZXTM::CLI::CLI( $wsdldir, $timeout );

# Connect right now? If in interactive mode, or if a hostname was supplied,
# then go right ahead
if( $host || $interactive ) {
   if( !$host && $standalone ) {
      dieWithUsage( "You must specify a traffic manager to connect to\n" );
   }

   my @cmd = ( 'connect', $host || '', $port || '', $user, $passwd, !$ssl );
   my( $err, $out ) = $cli->runCommand( \@cmd );

   # If we were using the commkey, try again with normal password auth.   
   # The traffic manager might not understand commkey auth (unlikely).
   if( $err && $use_commkey && $err !~ /^Failed to connect\./ ) {
      print "Commkey authentication failed - trying password authentication\n" if ( $verbose );
      $user   = undef;   # make connect use default user
      $passwd = undef;   # make connect prompt for password

      @cmd = ( 'connect', $host || '', $port || '', $user, $passwd, !$ssl );
      ( $err, $out ) = $cli->runCommand( \@cmd );
   }

   die "$err\n" if( $err );
   print $out . "\n" if( $interactive );

   # Add a banner if TM is running in Developer Edition Mode
   @cmd = ( "system.licensekeys.getCurrentLicenseKey" );
   ( $err, $out ) = $cli->runCommand( \@cmd );
   if(( !$err ) && isDeveloperEditionKey( $out )) {
      print( DeveloperEditionBanner() . "\n") if ( $interactive );
   }
}

if( $interactive ) {
   # Build a readline interface with tab completion
   $ENV{PERL_READLINE_NOWARN} = 1;
   $Term::ReadLine::termcap_nowarn = 1;
   $Term::ReadLine::termcap_nowarn = 1;
   $term = new Term::ReadLine( 'ZXTM' );
   &readline'rl_bind( 'M-h', 'Ding' );

   $attribs = $term->Attribs;
   $attribs->{completion_function} = sub { autoComplete( $cli, @_ ); };
   my $features = $term->Features();
   # Dont make the prompt stand out
   $term->ornaments( '0,0,0,0' ) if $features->{'ornaments'};
   $readline::rl_scroll_nextline = 0;
   $readline::rl_scroll_nextline = $readline::rl_scroll_nextline; # avoid warning
   my $histdir = $wsdldir ? $wsdldir : "$ENV{HOME}/.zcli";
   if( ! -e $histdir ) {
      mkdir( $histdir );
   }
   if( -d $histdir ) {
      $histfile = "$histdir/history";
      if( open( HISTORY, "<$histfile" )) {
         local $/ = undef;
         @readline::rl_History = split( /\n/, <HISTORY> );
         close( HISTORY );
      }
   }
   $SIG{TERM} = sub { $term->resettty(); exit; };
   # Don't need to reset the TTY on Ctrl+C - readline has already done
   # that
   $SIG{INT} = sub { exit; };
} else {
   if( defined( $script )) {
      open( SCRIPT, $script ) or die "Cannot read $script: $!\n";
   } else {
      open( SCRIPT, "<&STDIN" );
   }
}

# Treat Stdout as utf-8
binmode STDOUT, ':utf8';

# Main process loop
for( my $firsttime = 1 ;; $firsttime = 0 ) {
   if( $separator && !$firsttime ) {
      print "<EOF>\n";
      warn "<EOF>\n";
   }
   $cli->setInterrupt( 0 );
   $attribs->{screen_width} = getTerminalWidth() if( $term );
   my $cmd;
   if( $interactive ) {
      my $username = $cli->{user} eq $commkey_user ? "admin" : $cli->{user};
      my $prompt = $username . '@' . $cli->{host} . ' > ';
      $cmd = $term->readline( $prompt );
   } else {
      $cmd = <SCRIPT>;
   }
   last if( !defined( $cmd ));
   chomp( $cmd );
   print "$cmd\n" if( $verbose );
   $cli->setInterrupt( 0 );
   my( $args, $pipe ) = parseArguments( $cmd );
   if( !ref( $args )) {
      reportError( $args );
      next;
   }
   next if( !@$args );
   my $command = shift( @$args );
   if( ref( $command )) {
      reportError( "First argument must be a command, not a structure" );
      next;
   }

   # Refresh the commkey if needed
   if( $use_commkey ) {
      my @stat = stat( $commfile );
      my $now = time();

      if( !$passwd || $stat[9] != $commkeytime || $now < $commkeytime || $now == $stat[9] ) {
         local *COMM;
         if( open( COMM, "< $commfile" )) {
            $user = $commkey_user;
            $passwd = <COMM>;
            chomp( $passwd );
            $passwd = lc ( md5( $passwd ) );
            close( COMM );
            $commkeytime = $stat[9];
         }
      }
   }


   # If not connected yet, and the command isn't 'connect', then force
   # a connection to localhost
   if( !$cli->isConnected() && ( $command ne 'connect' )) {
      my( $err, $out ) = $cli->runCommand( [ 'connect', '', '', $user,
                                             $passwd, !$ssl ] );
      if( $err ) {
         reportError( $err );
         next;
      }
   }

   my @commands;
   if( $command =~ /\*/ ) {
      # Wildcard in the function to call. Expand it if possible
      @commands = expandMethods( $cli, $command );
   }
   @commands = ( $command ) if( !@commands );

   # Run each command in turn. Note that wildcards in the arguments are
   # expanded out per-command, because they may differ in meaning.
   # (unlikely that such a combination would work, though!)
   foreach $command ( @commands ) {
      $args = expandWildcards( $cli, $command, $args );
      if( !ref( $args )) {
         reportError( $args );
         next;
      }

      if( defined( $pipe )) {
         $pipe =~ s/^\s+//;
         my $openret;
         {
            local $SIG{__WARN__} = sub {};
            $openret = open( OUTPIPE, "|$pipe" );
         }
         if( $openret ) {
            disableTerminal() if( $interactive );
         } else {
            warn "Failed to send output to '$pipe': $!\n";
            open( OUTPIPE, ">&STDOUT" ) or die "Can't dup STDOUT: $!\n";
         }
      } else {
         open( OUTPIPE, ">&STDOUT" ) or die "Can't dup STDOUT: $!\n";
      }
      binmode( OUTPIPE, ':utf8' );

      my( $err, $out, $builtin ) = $cli->runCommand( [ $command, @$args ] );

      local $SIG{PIPE} = 'IGNORE';

      if( defined( $out )) {
         print Zeus::Dumper->Dump( [ $out ], [ 'Result' ] ) if( $debug );
         if( $formatoutput ) {
            if(( @commands > 1 ) && !$builtin ) {
               $out = { $command => $out };
            }
            if( $builtin ) {
               print OUTPIPE formatWrapped( $out );
            } elsif( !ref( $out )) {
               print OUTPIPE $out, "\n";
            } else {
               # Improve display: if the first input argument was an array,
               # then it is likely that the method was asking for data on
               # a list of objects (e.g. pools). So, index the output based
               # on the input list
               if(( ref( $out ) eq 'ARRAY' ) && @$args &&
                  ( ref( $args->[0] ) eq 'ARRAY' ) &&
                  ( @{$args->[0]} == @$out ) && @$out &&
                  ( ref( $args->[0]->[0] ) eq '' )) {
                  my %reshash;
                  for( my $i = 0; $i < @$out; $i++ ) {
                     $reshash{$args->[0]->[$i]} = $out->[$i];
                  }
                  $out = \%reshash;
               }
               print OUTPIPE formatDisplay( $out ), "\n";
            }
         } else {
            print OUTPIPE formatJSON( $out ), "\n";
         }
      }
      reportError( $err ) if( defined( $err ) && ( $err ne '' ));
      close( OUTPIPE );
      if( defined( $pipe )) {
         initTerminal() if( $interactive );
      }
   }
}
print "\n" if( $interactive );
