#!/bin/sh
#
# SOAP Callback client

# 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`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "soap-alert: 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 30

# ZXTM perl modules
BEGIN { 
   unshift( @INC, 
      "$ENV{ZEUSHOME}/zxtm/lib/perl",
      "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", 
      "$ENV{ZEUSHOME}/perl", 
   )
}

use Zeus::ZXTM::Utils qw( GetServerName );
use Zeus::ZXTM::ErrorDescriptions;   
use SOAP::Lite;
use Zeus::ZXTM::SOAPBase;
use Zeus::ZXTM::EventTypeUtils qw( getObjectTypes );
use Zeus::ZXTM::LogUtils qw( parseLogLine );
#use Zeus::Dumper;
use strict;

my $interface;
BEGIN {
   $interface = "AlertCallback";
   Zeus::ZXTM::SOAPBase::_addSerializerAndDeserializerForEnum( "$interface.Tag" );
   Zeus::ZXTM::SOAPBase::_addSerializerAndDeserializerForEnum( "$interface.ObjectType" );
   Zeus::ZXTM::SOAPBase::_addSerializerAndDeserializerForEnum( "$interface.Severity" );
}

# Prototypes
sub getParams(@);
sub usage(;$);
sub soapError();
   
## Parse Commandline parameters ##
my $params = getParams( @ARGV );

my $proxy = $params->{'proxy'} || $params->{'arg!proxy'};
die( "No proxy set.\n" ) unless( $proxy );

my $additional = $params->{'additional'} || $params->{'arg!additional'} || "";
my $username = $params->{'username'} || $params->{'arg!username'};
my $password = $params->{'password'} || $params->{'arg!password'} || "";
my $eventType = $params->{'eventtype'} || $params->{'arg!eventtype'} || "";

if( $username ) {
   $proxy =~ s/:\/\//:\/\/$username:$password@/;
}

my $data = $params->{'data'};
die( "No event passed.\n" ) unless( $data );

## Parse Log Line ##

my $parsed = parseLogLine( $data, 1 );

#die "[$data]\n" . Zeus::Dumper->Dump( [ $parsed ], ['parsed'] ) . "\n";

die( "Parsing alert failed.\n" ) unless( $parsed );
my $desc = $parsed->{msg};
my $severity = $parsed->{status};

# Setting up mapping from errors -> enum
my $errData = $Zeus::ZXTM::ErrorDescriptions::errors;
my %enumLookup;
foreach my $obj ( keys %$errData ) {
   foreach my $tag ( keys %{ $errData->{$obj} } ) {
      $enumLookup{ $tag } = "${obj}_${tag}";
   }
}
$enumLookup{ 'testaction' } = 'testaction';
$enumLookup{ 'CustomEvent' } = 'CustomEvent';

my( @tags, @objects, $primaryTag );

# Parse Objects
foreach my $obj ( @{ $parsed->{objs} } ) {
     
   my $type = $obj->{type}; 
   $type = "Unknown" unless( grep { $type eq $_ } getObjectTypes() );
   
   # Create SOAP data structures so mono works
   my $val =
      SOAP::Data->value( 
         SOAP::Data->name( "type" )
                   ->type( "zeusns:$interface.ObjectType" )
                   ->value( $type ),

         SOAP::Data->name( "name" )
                   ->type( "string" )
                   ->value( $obj->{name} ),

   );

   push @objects, SOAP::Data->type( "zeusns:$interface.Object" )
                            ->value( \$val );
}

# Parse Tags

#foreach my $tag ( @{ $parsed->{tags} } ) {
#   my $enum = $enumLookup{ $tag } || "Unknown";
#
#   if( !$primaryTag ) {
#      $primaryTag = $enum;
#   }
#   push( @tags, SOAP::Data->type( "zeusns:$interface.Tag" )
#                          ->value( $enum ) );
#}

# TODO (SFT) The non-primary tags have been removed as they are generally not used. 
# If they ever are used again, uncomment the code above.

$primaryTag = $enumLookup{ $parsed->{primary_tag} } || "Unknown";

my $soapTags = Zeus::ZXTM::SOAPBase::_createArray( "tags", "zeusns:$interface.Tag", \@tags );
my $soapObjs = Zeus::ZXTM::SOAPBase::_createArray( "objects", "zeusns:$interface.Object", \@objects );

## Send SOAP message ##
my $event = SOAP::Lite 
   -> uri('http://soap.zeus.com/AlertCallback/')
   -> proxy( $proxy )
   -> on_action(sub{join '', @_}) # Ditch the hash that's added by default
   -> on_fault( \&soapError );

my $time = Zeus::ZXTM::SOAPBase::_convertTime( time() );

my $method = SOAP::Data
   ->name('zeusac:eventOccurred')
   ->attr
   (  
      {  # Namespaces for Zeus objects/methods etc
         'xmlns:zeusac' => 'http://soap.zeus.com/zxtm/1.0/AlertCallback/',
         'xmlns:zeusns' => 'http://soap.zeus.com/zxtm/1.0/',
      } 
   )
;

$event->call( 
   $method =>
   (
      SOAP::Data->name( 'zeusac:zxtm'  => GetServerName() ), 
      SOAP::Data->name( 'zeusac:time'  => $time )->type( "xsd:dateTime" ), 
      SOAP::Data->name( 'zeusac:severity' => $severity )->type("zeusns:$interface.Severity"),       
      SOAP::Data->name( 'zeusac:primary_tag' => $primaryTag )->type("zeusns:$interface.Tag"),
      SOAP::Data->name( 'zeusac:tags' => $soapTags ),
      SOAP::Data->name( 'zeusac:objects' => $soapObjs ),
      SOAP::Data->name( 'zeusac:description' => $desc ),
      SOAP::Data->name( 'zeusac:additional' => $additional ),
      SOAP::Data->name( 'zeusac:event_type' => $eventType ),
   )
);

exit( 0 );

=item getParams(@)

Extract the paramaters passed in as a easily accessible hash table.
Will only work for --foo=bar type messages. The list passed in should
be the @ARGV list. Returns a reference to a hash.

=cut

sub getParams(@)
{
   my %params = ();
   my( $quotes, $quoteParam ) = ( 0, 0 );
   for my $p ( @_ ) {
      if( $quotes ) {
         $quotes .= " " . $p;
         if( $quotes =~ /\"$/ ) {
            $params{$quoteParam} = substr( $quotes, 0, -1 );
            ( $quotes, $quoteParam ) = ( 0, 0 );
         }
      } elsif( $p =~ /^--?h(elp)?$/ ) {
         usage();
         exit(0);

      } else {
         if( $p =~ /^[^-]/ ) {
            $p = "--data=$p"; 
         }
         if( $p =~ /^--?(\S+)=(.*)/ ) {
            my( $param, $val ) = ( $1, $2 );
            if( $val =~ /^\"/ && $val !~ /\"$/ ) {
               $quotes = substr( $val, 1 );
               $quoteParam = $param; 
            } else {
               $val =~ s/^\"|\"$//g;
               $params{$param} = $val;
            }
         }
      }
   }

   return \%params;
}

=item soapError()

Called when an error occurs in the soap call.

=cut

sub soapError()
{
   my( $soap, $res ) = @_;

   if( ! ref $res && $res ) {
      $res =~ s/\s+//;

      if( $res =~ /^not well-formed/ ) {
         $res =~ s/^.*?\n/Server returned an invalid response:\n/s;
      } elsif( $res =~ /syntax\serror.*byte\s0.*?\n(.*)$/s ) {
         $res = "Server returned: $1";
      }
      print STDERR "$res\n";
   } elsif( ref $res ) {
      my $err = $res->faultstring;
      $err =~ s/[\r\n]$//gs;
      print STDERR "A SOAP error ocurred, code: " . $res->faultcode . 
                   " ($err)\n";
   } else {
      print STDERR "A transport error occured\n";
   }

   exit(1);
}

=item 

Prints the usage + dies if passed an error.

=cut

sub usage(;$) 
{
   my( $error ) = @_;

   print <<EOF;
Usage: soap-alert args data

This script is used to send a soap alert to a SOAP server implementing the
http://soap.zeus.com/zxtm/1.0/AlertCallback interface.

REQUIRED Arguments:

-proxy=val       The address of the server implementing the SOAP
                 interface. E.g. http://server/soap
<data>           The alert message to send.

OPTIONAL Arguments:

-username=val    Username for basic http authorization. 
-password=val    Password for basic http authorization, you must also
                 set username for it to work.
-additional=val  Additional information to send to the soap server.

EOF

   die( $error ) if( $error );
}


