#!/usr/bin/perl
#    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.
#

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


@BigSister::common::options = ( "H", "s=s", "S=i", "o=s", "m=s", "t=s", "c=s", "h=s", "l=s" );
use lib "."; use lib "uxmon"; use lib "platforms"; 		#inslib
use BigSister::common;
proginit();

use strict;

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

my( $host, @users );

my $default_user = "sys";
$host = $BigSister::common::hostname;
chomp $host;

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

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

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

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

background() unless( $BigSister::common::dl );

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

alarm(0);
$SIG{"ALRM"} = sub { 
    BigSister::common::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;
}


