#!/bin/sh
# Documentation in perl code below.
# -*- perl -*-
# vim:set syn=perl:

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME
    OLD_PWD=`pwd`
    cd `dirname $0`
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "`basename $0`: FATAL: Cannot find Stingray Traffic Manager, check \$ZEUSHOME"
   exit 1
fi

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

#!perl -w #"
#line 28

=head1 NAME

S15afm - start/stop/restart the Stingray Application Firewall

An optional argument is --background, this will cause the init script to
daemonize to restart Stingray Application Firewall (useful if you don't
want to wait, it can take 10 seconds or more for a restart to complete.)

If you want no output generated by the script specify --quiet.

=head1 AUTHOR

Riverbed Technology, support@riverbed.com

=head1 COPYRIGHT

Copyright (C) 2009-2013, Riverbed Technology, Inc. All rights reserved.

=cut

BEGIN {
   # The shell code above ensures we have a ZEUSHOME set
   if ( not -d "$ENV{ZEUSHOME}/zxtm" ) {
      print STDERR "FATAL: No valid Stingray Traffic Manager install found, check \$ZEUSHOME";
      exit(1);
   }
   ($ENV{"ZEUSHOME"}) = ( $ENV{"ZEUSHOME"} =~ m@^(.*)$@ ); # Untaint
   unshift @INC,  "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
      "$ENV{ZEUSHOME}/perl";
   # The Application Firewall scripts require access to some programs in these directories
   $ENV{"PATH"} = "/bin:/usr/bin";

};


my( $quiet, $bg );

BEGIN {
   # Minimum version of the traffic manager this Application Firewall 
   # installation is compatible with
   my $MIN_VERSION = '8.0';

   # process command line arguments
   $bg = 0;
   if (grep /^--background$/, @ARGV) {
      $bg = 1;
      @ARGV = (grep !/^--background$/, @ARGV);
   }

   $quiet = 0;
   if (grep /^--quiet$/, @ARGV) {
      $quiet = 1;
      open(STDOUT, ">/dev/null");
      # Don't redirect STDERR - in quiet mode we should still get our own errors
      @ARGV = (grep !/^--quiet$/, @ARGV);
   }
   if (not -e "$ENV{ZEUSHOME}/zeusafm/current") {
      print STDERR "FAILED: Stingray Application Firewall install not found\n";
      exit(1);
   }

   # Check version compatiblity
   my( $current_version, $afm_version );
   eval {
      use Zeus::ZXTM::Version;
      $current_version = Zeus::ZXTM::Version::ZXTMVersion();
      $afm_version = readlink( "$ENV{ZEUSHOME}/zeusafm/current" );
      if( $afm_version =~ /zeusafm\/(\d+\.\d+)/ ) {
         $afm_version = $1;
      }
   };

   if( ! $afm_version || ! $current_version ) {
      print( STDERR 
         "FAILED: This installation of Stingray Application Firewall is " .
         "incompatible with the current version of Stingray Traffic Manager\n" 
      );
      exit( 1 );
   }

   if( $MIN_VERSION =~ /^(\d+)\.(\d+)/ ){
      my( $min_major, $min_minor ) = ( $1, $2 );
      
      if( $current_version =~ /^(\d+)\.(\d+)/ ) {
         my( $cur_major, $cur_minor ) = ( $1, $2 );
         if( $min_major > $cur_major || ( $min_major == $cur_major && $min_minor > $cur_minor ) ) {
            print( STDERR 
               "FAILED: Version $afm_version of Application Firewall is incompatible " .
               "with version $current_version of Stingray Traffic Manager\n" 
            );
            exit( ($ARGV[0]||'') eq 'stop' ? 0 : 1 );
         }
      }
   }

}

# Begin main code
use Fcntl ':flock';
use POSIX qw(setsid);
use Zeus::ZXTM::EventLog qw( logEvent ZLOG_SERIOUS ZLOG_INFO );
use Zeus::ZXTM::Flavour;
use Zeus::ZXTM::AFMUtils qw(
   getAFMPath
   getAFMVersion
   AFMEnabled
   AFMRunning
   AFMAdminServerURL
);

use strict;

if (scalar @ARGV != 1 or $ARGV[0] !~ /^(start|stop|restart)$/) {
   print STDERR "Usage: $0 (start|stop|restart) [--background] [--quiet]\n";
   exit(1);
}
if ($bg) {
   # daemonize the init process
   my $cpid = fork;
   if (not defined $cpid) {
      my $msg = "Stingray Application Firewall init script fork failure: $!";
      print STDERR "FAILED: $msg\n";
      logEvent( type => ZLOG_SERIOUS, tags => ['afm'], msg => $msg );
      exit(1);
   }
   if ($cpid) {
      my $ret = waitpid($cpid, 0);
      if ($ret != -1) {
         $ret = $? >> 8;
         if ($ret != 0) {
            my $msg = "Stingray Application Firewall init script child failure: code $ret";
            print STDERR "FAILED: $msg\n";
            logEvent( type => ZLOG_SERIOUS, tags => ['afm'], msg => $msg );
         }
         exit($ret);
      }
      exit(0); # child auto-reaped?
   }
   if (not setsid) {
      my $msg = "Stingray Application Firewall init script setsid failure: $!";
      print STDERR "FAILED: $msg\n";
      logEvent( type => ZLOG_SERIOUS, tags => ['afm'], msg => $msg );
      exit(1);
   }
   $SIG{CHLD} = 'IGNORE';
   chdir("/");
   open(STDIN,  "+>/dev/null");
   open(STDOUT, "+>&STDIN");
   open(STDERR, "+>&STDIN");
   $cpid = fork;
   if (not defined $cpid) {
      logEvent(
         type => ZLOG_SERIOUS,
         tags => ['afm'],
         msg => "Stingray Application Firewall init script 2nd fork failure: $!",
        );
      exit(1);
   }
   if ($cpid) {
      exit(0);
   }
   $SIG{CHLD} = 'DEFAULT';
}
my $action = $ARGV[0];
# using flock to avoid overlapping restarts... which can seriously
# break Stingray Application Firewall at the time of writing this
my $lockfile = "$ENV{ZEUSHOME}/zeusafm/init.lock";
my $svcscript = "$ENV{ZEUSHOME}/service.sh";
my $ret = open(LOCK, ">$lockfile");
if (not defined $ret) {
   my $msg = "Stingray Application Firewall $action: failed to open lockfile: $!";
   print STDERR "FAILED: $msg\n";
   logEvent( type => ZLOG_SERIOUS, tags => ['afm'], msg => $msg );
   exit(1);
}
my $waitlimit = 30; # 30 second limit waiting for restart lock
while(not flock(LOCK, LOCK_EX|LOCK_NB)) {
   if ($waitlimit == 0) {
      my $msg = "Stingray Application Firewall $action: timed out waiting for lock";
      print STDERR "FAILED: $msg\n";
      logEvent( type => ZLOG_SERIOUS, tags => ['afm'], msg => $msg );
      exit(1);
   }
   sleep(1);
   --$waitlimit;
}

# This command forces the Stingray Application Firewall to use the locally
# configured admin ports for contacting all cluster members, we run it every
# time we restart to ensure config changes take effect.  Use of this command
# is handled as a bit of a kludge, there's special-case code below to swallow
# any output and ignore errors
my $clustercfgcmd = getAFMPath();
if ((not $clustercfgcmd) && $action ne 'stop') {
   # guard against being used in non-configured state unless we're trying
   # to stop Stingray Application Firewall (when uninstalling we decouple
   # the config file before leaving the cluster and stopping Stingray
   # Application Firewall so that the new cluster password doesn't get
   # replicated across the config and so we don't get pool failure warnings)
   my $msg = "Stingray Application Firewall $action: Stingray Application Firewall is not configured";
   print STDERR "FAILED: $msg\n";
   exit(1);
}
if( not AFMEnabled() ) {
   if( $action ne 'stop' ) {
      # Do not (re)start if Stingray Application Firewall is not enabled
      my $msg = "Stingray Application Firewall is not enabled";
      print "$msg\n";
   }
   if( not AFMRunning() ) {
      exit(0);
   }
   $action = 'stop';
}
$clustercfgcmd .= "/bin/cluster_setup " .
   "$ENV{ZEUSHOME}/zxtm/conf/zeusafm.conf --set-all-admin-server-ports";

my @commands = (
   "$svcscript zeusafm $action"
  );
if ($action eq 'start') {
   unshift(@commands, $clustercfgcmd);
}
if ($action eq 'restart') {
   @commands = (
      "$svcscript zeusafm stop",
      $clustercfgcmd,
      "$svcscript zeusafm start",
     );
}
my $failed = 0;
for my $command (@commands) {
   $command .= ' 2>&1' if $quiet;
   my $output = `$command`; # let stderr leak to console (if not $quiet)
   my $status = $?;
   if ($command !~ /set-all-admin-server-ports/ and ($status & 127) != 0) {
      my $warn_msg = "Stingray Application Firewall $action: $command: exited on signal $!";
      print STDERR "FAILED: $warn_msg\n";
      print STDERR $output if $output;
      $failed = 1;
   } elsif ($command !~ /set-all-admin-server-ports/ and ($status >> 8) != 0) {
      my $ecode = ($status >> 8);
      my $warn_msg = "Stingray Application Firewall $action: $command: failed with code $ecode";
      print STDERR "FAILED: $warn_msg\n";
      print STDERR $output if $output;
      $failed = $ecode;
   }
   last if $failed;

   # make output look like other Stingray software init script output
   $output =~ s/^/ INFO   /mg if $output;
   if ($command =~ / stop$/) {
      print "Stingray Application Firewall Module stopped\n";
      #print $output;
   } elsif ($command =~ / start$/) {
      print "Stingray Application Firewall\n";
      print "Version " . getAFMVersion() . "\n";
      print $output;
   }
}

if (not $failed) {
   $action .= 'p' if $action eq 'stop';
   logEvent(
      type => ZLOG_INFO,
      tags => ['afm'],
      msg => "Stingray Application Firewall " . $action . "ed",
     );
} else {
   logEvent(
      type => ZLOG_SERIOUS,
      tags => ['afm'],
      msg => "Stingray Application Firewall $action failed",
     );
}
close(LOCK);
exit($failed);
