#!/usr/bin/perl -I/usr/lib/bs/bin -I/usr/lib/bs/uxmon
#    Big Sister network monitor
#    Copyright (C) 1998  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.
#

#=============================================================================
#
$main::Usage = "[-D debug] [-m message] [-s severity] [-h host|-u user]";
#
#=============================================================================


@main::options = ( "H", "s=s", "S=i", "o=s", "m=s", "t=s", "c=s", "h=s", "l=s" );
use common;
proginit();

use strict;

unless( $main::opt_l ) {
#    main::log( "error", "no line" );
#    exit(1);
$main::opt_l = "/dev/cua0";
}
my $linecommand="cu -s 9600 -l $main::opt_l";

my( $host, @users );

my $default_user = "sys";
$host = $main::hostname;
chomp $host;

my $dl = $main::dl;
my $extended_subject = $main::opt_H;
my $subject = $main::opt_s;
my $severity = $main::opt_S;
my $offender = $main::opt_o;
my $msgcode = $main::opt_c;
my $type = $main::opt_t."_";

my $message = $main::opt_m ? $main::opt_m:$subject;
($host = $main::opt_h) if( $main::opt_h );

unless( @users = @ARGV ) {
    main::log( "warning", "no pager destination" );
    exit(1);
}

if( $extended_subject ) {
    $subject = $host.": ".$subject;
}

background() unless( $main::dl );

my $pid;
my $pagermsg = "/".substr($message,0,16)."/5/3/1/1>";

alarm(0);
$SIG{"ALRM"} = sub { 
    main::log( "error", "timed out waiting for line" );
    kill( "HUP", $pid ) if( $pid );
    die;
};

foreach my $user (@users) {
    alarm(120);
    my $retry = 1;
    while( 1 ) {
	$pid = open( LINE, "|$linecommand" );
	last if( $pid
	    && (print  LINE "<$user".$pagermsg)
	    && (print LINE "\~\.")
	    && close( LINE ) );
	sleep 2;
    }
    alarm(0);
}



sub usage {
    exit 1;
}


sub untaint {
    my( $val ) = @_;
    $val =~ /^(.*)$/;
    return $1;
}


