package probes::WPing;

=head1 NAME

probes::WPing - WPing Probe for SmokePing

=head1 SYNOPSIS

 *** Probes ***
 + WPing
 data = /home/wping/

=head1 DESCRIPTION

Integrates WPing as a probe into smokeping. The variable B<data> must
point to your data directory containing the ping results.

=head1 AUTHOR

Norman Rasmussen <norman@rasmussen.org>

=cut

use strict;
use base qw(probes::base);
use Symbol;
use Carp;

sub new($$$)
{
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = $class->SUPER::new(@_);
    
    unless ( $ENV{SERVER_SOFTWARE} ) {
        
        croak "ERROR: WPing 'data' not defined in WPing probe definition"
            unless defined $self->{properties}{data};
        
        croak "ERROR: WPing 'data' does not point to an directory"
            unless -d $self->{properties}{data} and -r $self->{properties}{data};
        
        $self->{pingfactor} = 1000; # Gives us a good-guess default
        print "### assuming you are using an Windows Ping reporting in miliseconds\n";
    };
    
    return $self;
}

sub ProbeDesc($){
    return "Windows ICMP Echo Pings";
}

sub ping ($){
    my $self = shift;
    # do NOT call superclass ... the ping method MUST be overwriten
    my %upd;
    my $inh = gensym;
    my $outh = gensym;
    my $errh = gensym;
    # pinging nothing is pointless

    my @addresses = @{$self->addresses};
    return unless @addresses;
    
    $self->{rtts}={};
    while (@addresses) {
        my $t = pop @addresses;
        my @times = ();
        
        open PING, $self->{properties}{data}.$t;
        while (<PING>)
        {
            if (/Reply from.*time[=<](.*)ms/) {
                unshift (@times, $1);
            }
            if (/Request timed out/) {
                unshift (@times, "-");
            }
        }
        close PING;

        @times = map {sprintf "%.10e", $_ / $self->{pingfactor}} sort {$a <=> $b} grep {$_ ne "-"} @times;        
        map { $self->{rtts}{$_} = [@times] } @{$self->{addrlookup}{$t}} ;
    }
}

1;
