#!/bin/sh
#
# Mail the system administrator upon a failure

# 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 "alert-by-mail: 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

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

use Zeus::ZXTM::Spool;
use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::Utils qw( GetServerName );
use Zeus::ZXTM::Variant qw( getURLProductComponent );
use Zeus::ZXTM::Flavour qw( getProductName );
use Zeus::ZXTM::Configure;
use Zeus::ZXTM::EventTypeUtils qw( getObjectPrettyName_Single getObjectPrettyName getEditLink );
use Zeus::ZXTM::LogUtils qw( getParsedEvents parseLogLine );
use Zeus::ZXTM::AMP qw();
use Zeus::NetworkingUtils qw( isIPAddress HostToAddr SplitNode ); 
use ZeusOS;
#use Zeus::Dumper;
use strict;

sub wrap($;$);
sub Usage(;$);
sub cleanupanddie($$);
sub sendemail($$$$$$$$);
sub GetBrandLongname();

$| = 1;

# Important defines
my @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );

my $storage = new Zeus::ZXTM::StorageManager;
my $zconfig = $storage->getGlobalConfig();
my $zloc = $zconfig->get('location');
if( defined( $zloc ) && $zloc ne "" ) {
   $storage->setFallbackLocation( $zloc );
}

my $settings = $storage->getSettingsConfig();

my $retryLimit = $settings->get( 'notify!max_attempts' ) || 10; 

my $errData = $Zeus::ZXTM::ErrorDescriptions::errors;
my $shortName = getURLProductComponent();
$shortName = 'Zeus' if( $shortName eq 'ZXTM' );

# Check if any args (there shouldn't be any)
if ( @ARGV ) {
   if ( $ARGV[0] =~ /^--help|-h$/ ) {
      Usage( *STDOUT );
      exit(0);
   }
   Usage();
   exit(1);
}

my $spool = new Zeus::ZXTM::Spool;
if(!$spool->havePermissions() ) {
   die "Invalid permissions to process the spool\n";
}
my $num_messages_per_mail = 100;
$spool->setMaxEntries( 10000 );

my $entry = $spool->Next();

while ( defined( $entry ) ) {
   # Parse alert entries in spool directory
   my @entries = ();
   my %messages = ();

   for( my $i = 0; defined( $entry ) && $i < $num_messages_per_mail; $entry = $spool->Next(), ++$i ) {
      my %entryHash = %{$entry};
      my( $toList, $sender, $server, $time, $body, $alertname, $action, $timeout, $verbose ) = 
         @entryHash{ qw( to sender server time body eventtype action timeout verbose )  };
   
      if( $action ) {
         my $aconf = $storage->getActionConfig( $action );
   
         cleanupanddie( $entry, "actions/$action\tCould not find action configuration for '$action'" )
            unless $aconf;
         cleanupanddie( $entry, "actions/$action\tSupplied action must be of type 'email'" )
            unless $aconf->get( 'type' ) eq "email";
   
         # Server
         $server = $aconf->get( 'server' );
         cleanupanddie( $entry, "actions/$action\tAction '$action' does not have valid 'server' configuration, e-mail failed to send" )
            unless( $server );
   
         # Sender
         $sender = $aconf->get( 'from' );
         cleanupanddie( $entry, "actions/$action\tAction '$action' does not have valid 'from' configuration, e-mail failed to send" )
            unless( $sender );
   
         # Recipients
         $toList = [ $aconf->getList( 'to' ) ];
         cleanupanddie( $entry, "actions/$action\tAction '$action' does not have valid 'to' configuration, e-mail failed to send" )
            unless( @$toList );
   
         $timeout = $aconf->get( 'timeout' );
   
         $verbose = ($aconf->get( 'verbose' ) =~ /^y/i ) ? 1 : 0;
      }
   
      # If we fail to send a entry add the failed to address in here
      $entry->{failed} = [];
   
      # We'll remove this from the spool later
      push @entries, $entry;
   
      # Don't try to send email about failure to send email
      # (TODO: potentially relax this to email person A about failure to email person B)
      next if $body =~ /\temailscript(fail|out)\t/;
   
      for my $to ( @$toList ) {
         my $key = "$to|$sender|$server";
   
         # Entries to the same place from the same server and address get
         # bundled in the same message
         unless( $messages{$key} ) {
            $messages{$key} = {};
            $messages{$key}->{msg} = "";
            $messages{$key}->{count} = 1;
            $messages{$key}->{entry} = [];
            $messages{$key}->{status} = {};  # only records which objects are relevant
            $messages{$key}->{alertnames} = {};
            $messages{$key}->{eventdescs} = [];
            $messages{$key}->{timeout} = 0;
            $messages{$key}->{verbose} = 0;
         } 
   
         push( @{$messages{$key}->{entry}}, $entry );
         $messages{$key}->{alertnames}->{$alertname}->{$action}++;
   
         my $message = $messages{$key}->{msg};
         my $count = $messages{$key}->{count};
   
         # Parse log and get a short description for the email subject
         my $bodychomped = $entry->{body};
         chomp $bodychomped;
         my $parsed = parseLogLine( $bodychomped, 1 );
         my $shortdesc = $bodychomped;
         $shortdesc =~ s/.*\t//;  # fallback: last tab-delimited component
   
         if( $parsed && $parsed->{primary_obj} && $parsed->{primary_tag} ) {
            my $objtype = $parsed->{primary_obj}->{type};
            my $eventid = $parsed->{primary_tag};
            my $errEntry = $errData->{$objtype}->{$eventid};
            $shortdesc = $errEntry->{prettyname} if( $errEntry && $errEntry->{prettyname} );
         }
         unshift @{$messages{$key}->{eventdescs}}, $shortdesc;
   
         $message .= "\n" unless( $count == 1 ); # Add spacers between entries
   
         # Format time info
         my @time = localtime( $entry->{time} );
         my $time = sprintf( "%s %02d %02d:%02d:%02d", $months[$time[4]], 
                             $time[3], $time[2], $time[1], $time[0] );
   
         my $msg = sprintf( "#%d %s: ", $count++, $time );
   
         my $padding = length( $msg );
              
         # Prettify objects & store objects so we can talk about them later. 
         my @formatedParts;
         foreach my $obj ( @{$parsed->{objs}} ) {
            $messages{$key}->{status}->{"$obj->{type}|$obj->{name}"} = 1;
   
            my( $href, $name, $typePretty ) = getEditLink( $obj->{type}, $obj->{name} );
   
            my $pretty = $typePretty;
            $pretty .= " '$name'" if( $name ); 
          
            unshift( @formatedParts, $pretty );
         }
   
         # Format Body
         my $body = "";
         $body .= "$parsed->{status}  " if( $parsed->{status} );
         $body .= join( ", ", @formatedParts );
   
         $body = wrap( $body, 75 - $padding );
         $body .= wrap( $parsed->{msg} , 75 - $padding ) if( $parsed->{msg} );
   
         $body =~ s/\n(.)/ "\n" . (' ' x $padding) . $1 /egms;
         $msg .= $body;
         $message .= $msg;
   
         $messages{$key}->{msg} = $message;
         $messages{$key}->{count}++;
         $messages{$key}->{verbose} ||= $verbose;
   
         # Use the highest timeout
         if( $timeout > $messages{$key}->{timeout} ) {
            $messages{$key}->{timeout} = $timeout;
         }
      }
   }

   # No messages to send? Just exit.
   exit(0) unless( scalar keys %messages );

   my @errors = ();

   # Get status from AMP State of the world.
   my $sotw = Zeus::ZXTM::StateCache::getStateOfTheWorld( ['localhost'], undef, 1 );
   my %runningVSs = map { $_ => 1 } @{$sotw->{localhost}->{running}};

   my %failedNodes = map {
      my @split = split( /\s+/, $_ );
      $split[0] => \@split; 
   } @{$sotw->{localhost}->{failednodes}};

   my %confErrors;
   foreach my $err ( @{$sotw->{localhost}->{errors}} ) {
      my @split = split( /\t/, $err );
      
      next if( scalar @split < 4 );
      
      $confErrors{$split[0]}->{$split[4]} = 1; 
   }

   my %vservers = map{ $_ => $storage->getVSConfig( $_ ); } $storage->getAllVSNames();
   my %pools = map{ $_ => $storage->getPoolConfig( $_ ); } $storage->getAllPoolNames();
   my( %poolStatus, %nodeStatus, %poolNodes, %nodeAlias, %aliasLookup );

   # Store the status strings of nodes and pools so we only have to process them once.
   foreach my $pool ( keys %pools ) {
      my @nodes = sort $pools{$pool}->getList( 'nodes' );
      my @failed = grep { $failedNodes{$_} } @nodes;
      my $s;
   
      my @confErrs = keys( %{ $confErrors{"pools/$pool"} } );
   
      if( scalar @failed == 0 && scalar @confErrs == 0 ) {
         $s = "OK";
      } elsif( scalar @failed == scalar @nodes ) {
         $s = "Failed: All nodes have failed";
      } elsif( scalar @failed ) {
         $s = "Partial Fail: Some nodes have failed";
      } elsif( scalar @confErrs ) {
         $s = "Config Error: " . join( ", ", @confErrs );
      }   # TODO Return tag?
   
   
      $poolStatus{$pool} = $s;
      $poolNodes{$pool} = \@nodes;
   
      foreach my $node ( @nodes ) {
         next if( $nodeStatus{$node} );
         my @confErrsNode = keys( %{ $confErrors{"nodes/$node"} } );
   
         if( $failedNodes{$node} ) {
            $nodeStatus{$node} = "Failed"; 
         } elsif( scalar @confErrsNode ) {
            $nodeStatus{$node} = "Config Error: " . join( ", ", @confErrsNode );
         } else {
            $nodeStatus{$node} = "OK";
         }     
   
         # If this node uses a host name, resolve it and  store the ip addresses.
         # Because ZXTM allways uses the IP address (not the host name) when reporting
         # problems, we have to print both hostname and IP.
         my( $host, $port ) = SplitNode( $node );
         if( $host && $port && !isIPAddress( $host ) ) {
            my @addrs = HostToAddr( $host );
            foreach my $addr( @addrs ) {
               push( @{$nodeAlias{$node}}, "$addr:$port" );
               $aliasLookup{"$addr:$port"} = $node;
            }
         }
      }
   }


   # Loop through all the messages sending them
   foreach my $key ( keys %messages ) {
   
      # Finish building email messsage
      my $message = $messages{$key}->{msg};
      my $status = $messages{$key}->{status};
   
      my( $to, $sender, $server ) =  split( /\|/, $key );
   
      $message = "All alert messages (oldest first):\n"
         . ('-' x 76) . "\n" . $message . ('-' x 76) . "\n";
   
      #$message .= "\n" . Zeus::Dumper->Dump( [$sotw], ['SOTW'] );
   
      # Build Status Message
      sub sortObjs {
         my( $aV, $bV ) = ( 0, 0 );
         $aV = 30 if( $a =~ /^vservers/ );
         $bV = 30 if( $b =~ /^vservers/ );
         $aV = 20 if( $a =~ /^pools/ );
         $bV = 20 if( $b =~ /^pools/ );
         return $bV - $aV;
      }
   
      # Loop through all the objects this messsage references.
      my $statusMessage = "";
      my %seen;
      foreach my $statKey ( sort sortObjs keys( %{$status} ) ) {
         my( $obj, $name ) = split( /\|/, $statKey, 2 );
         next unless( $obj =~ /^(vservers|pools|nodes)$/ );
         next if( $seen{$statKey} );
   
         # Display the status of vserver/pools/nodes. For vservers and pools
         # we display a hierarchy showing the objects child pools & nodes.
   
         # Virtual Server Status
         my $s = "Unknown";
         if( $obj eq 'vservers' && $vservers{$name} ) {
            my @confErrs = keys( %{ $confErrors{"vservers/$name"} } );
   
            if( ($vservers{$name}->get( 'enabled' )||'N') =~ /^y/i ) {
               $s = ( $runningVSs{$name} ? "OK":"Down (Should be running)" );
            } else {
               $s = ( $runningVSs{$name} ? "Up (Should be stopped)":"Stopped" );
            }
   
            if( $s eq 'OK' && scalar @confErrs ) {
               $s = "Config Error: " . join( ", ", @confErrs );
            }
            
            # Render Pools used by this VS
            my %vsPools = $storage->getPoolsUsedByVS( $name );
            foreach my $pool ( sort keys %vsPools ) {
               next unless $pool;
               $seen{"pools|$pool"} = 1;
   
               if( $pool eq "discard" ) {
                  $s .= "\n + Pool 'discard'";
               } else {
                  $s .= "\n + Pool '$pool' = $poolStatus{$pool}";
   
                  foreach my $node ( sort @{$poolNodes{$pool}} ) {
                     my $ns = $nodeStatus{$node} || "Unknown";
                     $s .= "\n    + Node '$node' ";
               
                     # Print out ip address if the node uses a hostname
                     if( $nodeAlias{$node} ) {
                        $s .= "(" . join( ', ', @{$nodeAlias{$node}} ) . ") ";
                     }
                     $s .= "= $ns";
                     $seen{"nodes|$node"} = 1;
                  }
               }
            }
   
            my $objPretty = getObjectPrettyName_Single( $obj ) || $obj;
            $statusMessage .= "$objPretty '$name' = $s\n";
         
         # Pool Status
         } elsif( $obj eq 'pools' && $pools{$name}  ) {
            $s = $poolStatus{$name};
   
            # Work out status of each child node
            foreach my $node ( @{$poolNodes{$name}} ) {
               my $ns = $nodeStatus{$node} || "Unknown";
               $s .= "\n + Node '$node' ";
   
               # Print out ip address if the node uses a hostname
               if( $nodeAlias{$node} ) {
                  $s .= "(" . join( ', ', @{$nodeAlias{$node}} ) . ") ";
               }
               $s .= "= $ns";
               $seen{"nodes|$node"} = 1;
            }
         
            my $objPretty = getObjectPrettyName_Single( $obj ) || $obj;
            $statusMessage .= "$objPretty '$name' = $s\n";
   
         # Nodes Status
         } elsif( $obj eq 'nodes' ) {
            $s = $nodeStatus{$name};
            unless( $s ) {
               $name = $aliasLookup{$name} || $name;
               next if( $seen{"$obj|$name"} );
               $s = $nodeStatus{$name} || 'Unknown';
            }
   
            my $objPretty = getObjectPrettyName_Single( $obj ) || $obj;
            $statusMessage .= "$objPretty '$name' ";
               
            # Print out ip address if the node uses a hostname
            if( $nodeAlias{$name} ) {
               $statusMessage .= "(" . join( ', ', @{$nodeAlias{$name}} ) . ") ";
            }
   
            $statusMessage .= "= $s\n";
         }
      }
   
      if( $statusMessage ) {
         $statusMessage = "Current status of referenced Virtual Servers, Pools & Nodes:\n"
               . ('-' x 76) . "\n" . $statusMessage . ('-' x 76) . "\n\n";
      }
   
      # Email Headings
      my $hostname = GetServerName();
   
      $sender = lc( $shortName ) . '@%hostname%' unless $sender;
      $sender =~ s/\Q%hostname%\E/$hostname/gi;
      $sender =~ s/\Q%ip%\E/$hostname/gi;  # GLB
   
   
      my $confs = '';
      my $num = 0;
      foreach my $alertname ( sort keys %{$messages{$key}->{alertnames}} ) {
         next if $alertname eq ".Test Settings";
         my $hash = $messages{$key}->{alertnames}->{$alertname};
         foreach my $action ( sort keys %$hash ) {
            $confs .= ( ' ' x 3 ) . "$alertname -> $action\n";
            $num++;
         }
      }
   
      $confs  = "\nThis message was sent by the following Alert mapping" .
          ( $num > 1 ? 's' : '' ) . ":\n" . $confs if $num > 0;
   
      my $longname = GetBrandLongname();
      my $email = <<EOF;
$longname Alert messages from $hostname.

$statusMessage$message$confs
EOF

      my $subject = '';
      my $maxsubject = 80;
      my $numevents = scalar @{$messages{$key}->{eventdescs}};
      while( length( $subject ) < $maxsubject && scalar @{$messages{$key}->{eventdescs}} ) {
         my $event = shift @{$messages{$key}->{eventdescs}};
         my $count = 1;
         while( @{$messages{$key}->{eventdescs}} && ${$messages{$key}->{eventdescs}}[0] eq '$event' ) {
            $count++;
            shift @{$messages{$key}->{eventdescs}};
         }
         $subject .= "${count}x " if $count > 1;
         $subject .= $event;
         $subject .= ", ";
      }
      $subject =~ s/, $//g; # Drop the last ", "
   
      # If there are still events to report then put a ... after the end
      # of the subject
      if( length( $subject ) >= $maxsubject && scalar @{$messages{$key}->{eventdescs}} ) {
         $subject = "$numevents events: ${subject}...";
      }
      $subject=~ s/[\n\r]/ /g;
   
      $subject = "$shortName: $subject";
   
      # Collect server info and send
      my ($port) = scalar getservbyname( 'smtp', 'tcp' ) || 25;
      if( $server =~ s/^(.*):(\d+)$/$1/ ) {
         $port = $2;
      }
   
      my @toArray = split /[,\s]+/, $to;
   
      my $ret;
      eval {
         local $SIG{ALRM} = sub { die "timeout\n" };
         alarm( $messages{$key}->{timeout} )
             if( $messages{$key}->{timeout} );
   
         $ret = sendemail($server, $port, $hostname, $sender,
                          \@toArray, $subject, $email, $messages{$key}->{verbose});
      };
      alarm( 0 );
      if( $@ ) {
         $ret = "$@";
         chomp $ret;
      }
   
      if( $ret ) {
         if( $messages{$key}->{verbose} ) {
            print "Email failed to send: $ret\n";
         }
   
         my @actions = ();
         foreach my $alertname ( sort keys %{$messages{$key}->{alertnames}} ) {
            next if $alertname eq ".Test Settings";
            my $hash = $messages{$key}->{alertnames}->{$alertname};
            @actions = ( sort keys %$hash );
         }
   
         if( scalar @actions ) {
            foreach my $action( @actions ) {
               push( @errors, "actions/$action\tFailed to send e-mail: $ret" );
            }
         } else {
            push( @errors, "Failed to send e-mail via server $server: $ret" );
         }
   
         foreach my $entry ( @{$messages{$key}->{entry}} ) {
            push( @{$entry->{failed}}, $to );
            #print "FAILED: [$to] [$entry->{fails}/$retryLimit]\n";
         }
      }
   }

   # Delete all entries, if a messsage failed to send, re-add it to the spool dir
   foreach my $entry ( @entries ) {
      $spool->DeleteEntry( $entry );
      if( scalar @{$entry->{failed}} ) {
   
         # If it was a test email, don't re-add it
         next if $entry->{body} =~ /\ttest\//;
   
         # If it fails too many times, don't bother re-adding it
         if( $entry->{fails} + 1 >= $retryLimit ) {
            push(@errors, "Email exceeded send attempt limit ($retryLimit) and was " .
                          "removed from send queue." );
            next;
         }
   
         my $ret = $spool->addAlert(
            $entry->{body}, $entry->{time}, $entry->{failed}, $entry->{sender},
            $entry->{server}, $entry->{port}, $entry->{eventtype}, $entry->{action},
            ++$entry->{fails}
         );
         if( $ret ) {
            push(@errors, "$ret; Failed email could not be re-added to the send queue." );
         }
      }
   }

   if( scalar @errors ) {
   die( join( "\n", @errors ) . "\n" );
   }
   
}

exit(0);


# ------------------------------------------------------------

# Send an email.
# Returns undef on success, or an error text if it failed
sub sendemail($$$$$$$$)
{
   my( $addr, $port, $hostname, $from, $to, $subject, $body, $debug ) = @_;

   my $proto      = getprotobyname( 'tcp' );
   my $host_iaddr = gethostbyname( $addr ) or 
       return "Failed to look up hostname '$addr'";

   $debug ||= $ENV{SMTP_DEBUG};

   # Calculate timezone offset
   my $timenow = time();
   my @localtime = localtime( $timenow );
   my $localtimenow = Zeus::TimeLocal::timegm( @localtime );
   my $diff = ( $localtimenow - $timenow ) / 60;
   my $hours = int( $diff / 60 );
   $hours = -$hours if( $hours < 0 );
   my $mins = int( $diff % 60 );
   my $zoneoffset = sprintf( "%s%02d%02d", ( $diff > 0 ) ? '+' : '-',
                             $hours, $mins );

   my @time       = localtime();
   my $date       = sprintf( "%d %s %d %02d:%02d:%02d %s",
                             $time[3], $months[$time[4]], $time[5] + 1900,
                             $time[2], $time[1], $time[0], $zoneoffset );

   my $host_paddr = ZeusOS::pack_sockaddr_in( $port, $host_iaddr );

   print "SMTP session start:\n" if $debug;
   print "-> Connecting to $addr:$port\n" if $debug;

   socket( SOCKET, $ZeusOS::PF_INET, $ZeusOS::SOCK_STREAM, $proto )
       or return "Failed to open email socket: $!";

   my $connect = connect( SOCKET, $host_paddr);

   return "Failed to connect to $addr:$port: $!" unless( $connect );

   print "<- Connected to $addr:$port\n" if $debug;

   my $resp = "";

   # read greeting
   print "<- " if $debug;
   while( $resp !~ /\n$/ ) {
      my $buf;
      my $bytes = sysread SOCKET, $buf, 4196;
      return "Read from SMTP server '$addr' failed: $!" if( $bytes < 0 );
      $resp .= $buf;

      print $buf if $debug;
   }

   my $to_string = join ', ', @$to;

   my $msg = <<EOF;
To: $to_string
From: $from
Date: $date
Subject: $subject
X-ZXTM-Notify: $hostname
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8

$body
EOF
   # Now remove references to special characters that might cause our mail
   # program to do something we don't want it to
   $msg =~ s/^\./../mg;
   $msg =~ s/[\x00-\x08\x0B-\x1F]//g;

   my @rcpt_to = map { "RCPT TO:<$_>\r\n" } @$to;

   my $valid_addresses = 0;

   # rebuild $msg with \r\n as line feeds (bug 5088)
   my $fixed_msg = '';
   foreach my $line( split '^', $msg ) {
      $line =~ s/\r?\n$//s;
      $fixed_msg .= "$line\r\n";
   }


   # write line; read response
 TALK: foreach my $data (
      "HELO $hostname\r\n",
      "MAIL FROM:<$from>\r\n",
      @rcpt_to,
      "DATA\r\n",
      "$fixed_msg\r\n.\r\n",
      "QUIT\r\n" ) {

      if( $data =~ /^DATA/ && ! $valid_addresses ) {
         return "No valid addresses provided";
      }

      my $line = $data;
      print "-> " if $debug;
      while( length $line ) {
         my $bytes = syswrite SOCKET, $line, length $line;
         return "Failed to write to SMTP server '$addr': $!" if( !defined($bytes) );
         print substr $line, 0, $bytes if $debug;
         $line = substr $line, $bytes;
      }

      my $resp = "";
      print "<- " if $debug;
      while( $resp !~ /\n$/ ) {
         my $buf;
         my $bytes = sysread SOCKET, $buf, 4196;
         if( !defined $bytes || $bytes <= 0 ) {
            if( defined $bytes && $bytes == 0 ) {
               if( $data =~ /^QUIT/ ) {
                  last TALK;
               }
               return "Read from SMTP server '$addr' failed: EOF";
            }
            return "Read from SMTP server '$addr' failed: $!";
         }

         $resp .= $buf;

         print $buf if $debug;
      }
      if( $resp !~ /^(\d+)/ || $1 >= 400 ) {
         $resp =~ s/\s+$//s;
         if( $data =~ /RCPT TO: (.*?)\s+/s ) {
            my $address = $1;
            $resp =~ s/$address//;
            $resp =~ s/^[\s\d:]+//;
            warn "Server rejected email address '$address': $resp\n";
         } else {
            return "SMTP server '$addr' returned an error: $resp";
         }
      } else {
         if( $data =~ /^RCPT TO/ ) {
            $valid_addresses++;
         }
      }
   }

   print "SMTP session end\n" if $debug;
   close( SOCKET );

   return undef;
}


# ------------------------------------------------------------

=item ReadBranding

Read the branding file

=cut

sub GetBrandLongname()
{
   my $BRANDING_FILE = "$ENV{ZEUSHOME}/zxtmadmin/lang/_default/branding";
   my $LONGNAME = getProductName();

   if( -f "$BRANDING_FILE" ) {
      open FILE, "$BRANDING_FILE";
      while (<FILE>) {
         chomp;
         next unless /^([^=]+)=(.*)/;
         my( $key, $val ) = ( $1, $2 );
         $val =~ s/"//g;
         $LONGNAME  = $val if $key eq 'LONGNAME';
      }
      close FILE;
   }

   return $LONGNAME;
}

# ------------------------------------------------------------

sub Usage(;$)
{
   my $fh = shift || *STDERR;

   print $fh <<EOF;
Usage: alert-by-mail [--help]

This script will read the spool directory and email any pending
alerts to the sysadmin.

The email address that is used for the emails can be changed by
altering the setup of your Email Actions.
EOF
   
}

# Wrap some text to 76 chars, or whatever the second argument is
# This will does NOT hard wrap words that are longer than the
# limit.
sub wrap($;$)
{
   my ( $text, $num ) = @_;
   $num = 75 unless defined $num;

   if ( $num <= 0 ) {
      $text =~ s/\n+$/\n/s;
      return $text;
   }

   my @paragraphs = ();
   my $paragraph = '';
   foreach my $line ( split /^/, $text ) {
      $line =~ s/\s+$//;
      if ( length $line == 0 ) {
         # Empty line - new paragraph
         push @paragraphs, $paragraph if length $paragraph;
         push @paragraphs, ''; # preserve blank line
         $paragraph = '';
         next;
      } elsif( $line =~ /^\s+\S+$/ ) {
         # indented line - new paragraph
         push @paragraphs, $paragraph if length $paragraph;
         $paragraph = $line;
         next;
      }
      # Normal line, add on to current text
      $paragraph .= ' ' if length $paragraph;
      $paragraph .= $line;

      if ( length $line < 40 ) {
         # Short line, force a new paragraph
         push @paragraphs, $paragraph if length $paragraph;
         $paragraph = '';
      }
   }
   push @paragraphs, $paragraph if length $paragraph;

   foreach ( @paragraphs ) {
      next unless $_;
      s/(.{1,$num})(\s+|$)/$1\n/msg;
      s/\n+$//;
   }

   return join( "\n", @paragraphs ) . "\n";
}


# ---------------------------------------------------

sub cleanupanddie($$) {
   my ( $entry, $msg ) = @_;
   $spool->DeleteEntry( $entry );
   $msg .= "\n" unless $msg =~ /\n$/s;
   die $msg;
}


