package Monitor::cmd;

require 5.001;
require Exporter;

use strict;
use vars qw(@ISA @EXPORT $VERSION);
use FileHandle;

@ISA = qw(Exporter Monitor::Monitor);


sub new
{
    my ($this, $timeout) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};

    bless($self, $class);
    $timeout=15 unless( $timeout );

    $self->{"htable"} = [];
    $self->{"timeout"} = $timeout;

    return($self);
}


sub add_check {
    my( $self, $item, $cmd, @res ) = @_;
    my( $htable ) = $self->{"htable"};

    $item = "$uxmon::hostname.cmd" unless( $item );
    push( @$htable, [ $item, $cmd, @res ] );
}



sub check {
    my( $self ) = @_;
    my $htable = $self->{"htable"};
    my( $check );
    my( $match );
    my( $item, $cmd, @res, $retval, $text, $pid );
    my $fh = new FileHandle;

    foreach $check (@$htable) {
	($item,$cmd,@res) = @$check;
	$retval = "timeout";
	$text = "";
	eval {
	    $SIG{"ALRM"} = sub { die; };
	    Platform::bsalarm( $self->{"timeout"} );
	    $pid = open( $fh, "$cmd 2>&1|" );
	    if( $pid ) {
		while( <$fh> ) {
		    $text .= $_;
		}
		close $fh;
		undef $pid;
		$retval = ($?>>8);
	    }
	    else {
		$retval = "failed";
	    }
	};
	$SIG{"ALRM"} = "IGNORE";
	if( $pid ) {
	    kill( "HUP", $pid );
	    sleep 1;
	    kill( "TERM", $pid );
	}
	my $try;
	foreach $try (@res) {
	    if( ($try->[0] eq $retval) || ($try->[0] eq "*") ) {
		$match = $try;
		last;
	    }
	    next if( ($try->[0] =~ /^\d+$/)
		     || grep( $try->[0] eq $_, "timeout", "failed" ) );
	    eval {
		if( $text =~ /$try->[0]/ ) {
		    $match = $try;
		    last;
		}
	    }
	}
	if( $match ) {
	    $self->report( $item, $BigSister::common::status_codes{$$match[1]}, $$match[2] );
	    $self->report( $item, 100, $text ) if( $text );
	}
    }
}




1;
