package Requester::CommandWatchRequester;

use strict;
use Requester::WatchRequester;
use FileHandle;

@Requester::CommandWatchRequester::ISA = qw(Requester::WatchRequester);

my $timeout = 10;

sub start_sensor {
    my( $self, $handle, $duration ) = @_;
    unless( $handle ) {
        $handle = { "file" => new FileHandle() };
    }
    $handle->{"duration"} = $duration;
    my $cmd = $self->command( $duration );
    print "start_sensor() starting $cmd\n" if( $BigSister::common::dl > 4 );
    my $pid = $handle->{"pid"} = open( $handle->{"file"}, "$cmd|" );
    $handle->{"etc"} = $duration + time;
    return $handle;
}


sub request {
    my( $self, @args ) = @_;
    my( $env, $domain, $variables ) = @args;

    my $cmd = $env->expand_value( "command" );
    $self->set_command( $cmd ) if( $cmd );
    return( $self->SUPER::request( @args ) );
}



sub set_command {
    my( $self, $command_template ) = @_;

    $self->{"CommandWatchRequester::command_template"} = $command_template;
}


sub command {
    my( $self, $duration ) = @_;

    return( sprintf( 
        $self->{"CommandWatchRequester::command_template"},
        $duration )
    );
}


sub getresults {
    my( $self, $handle ) = @_;

    return undef unless( $handle->{"pid"} );
    return undef if( $handle->{"etc"} > time );
    my @text = ();
    my $kill = 1;
    eval {
        $SIG{"ALRM"} = sub { die; };
	Platform::bsalarm( $timeout );
	my $file = $handle->{"file"};
	while( <$file> ) {
	   chomp;
	   push( @text, $_ );
	}
	$SIG{"ALRM"} = "IGNORE";
	Platform::bsalarm(0);
	$kill = 0;
    };
    kill( "TERM", $handle->{"pid"} ) if( $kill );
    close( $handle->{"file"} );

    return( $self->parse( \@text, $handle->{"duration"} ) );
}


# stop a sensor started with start_sensor() without polling for results
# via getresults()
sub abort_sensor {
    my( $self, $handle ) = @_;

    print "aborting sensor: ".($self->command())."\n" if( $BigSister::common::dl > 4 );
    if( $handle->{"pid"} ) {
        kill( "TERM", $handle->{"pid"} );
	close( $handle->{"file"} );
    }
    print "  done\n" if( $BigSister::common::dl > 6 );
}

1;
