#!/usr/bin/perl
#    Big Sister network monitor
#    Copyright (C) 1998-2002  Thomas Aeby
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

$BigSister::common::Usage = "[-h host]";

@BigSister::common::options = ( "h=s" );
use lib "$ENV{BIGSISTER_CHROOT}/usr/share/bigsister/bin"; use lib "$ENV{BIGSISTER_CHROOT}/usr/share/bigsister/uxmon"; #inslib
use BigSister::common;
use Net::SMTP;

proginit();

my $Mailhost = $opt_h;
$Mailhost = $ENV{"BS_EV_mailhost"} unless( $Mailhost );
unless( $Mailhost ) {
    BigSister::common::log( "err", "no mailhost" );
    exit(1);
}
$Input = $ENV{"INPUTFILE"};
if( $Input ) {
    close STDIN;
    open( STDIN, "<$Input" );
}

my $users;
my $smtp = Net::SMTP->new($Mailhost); # connect to an SMTP server
$smtp->mail( "bigsister" );     # use the sender's address here
while( @ARGV ) {
    my $user = shift;
    $users .= "," if( $users );
    $users .= $user;
    $smtp->to($user);        # recipient's address
}
$smtp->data();                      # Start the mail

# Send the header.
#
my %headers = ();
while( <STDIN> ) {
    chomp;
    last unless( $_ );
    if( /^([^\s\t]+):/ ) {
        $headers{$1} = 1;
    }
    $smtp->datasend( $_."\n" );
}

$smtp->datasend("To: ".join(", ",split(" ",$users))."\n") unless( $headers{"To"} );
$smtp->datasend("From: Big Sister <bigsister>\n") unless( $headers{"From"} );
$smtp->datasend("Subject: $subject\n") unless( $headers{"Subject"} );
$smtp->datasend("\n");

# Send the body.
#
while( <STDIN> ) {
    $smtp->datasend($_);
}

$smtp->dataend();                   # Finish sending the mail
$smtp->quit;                       
