#!/usr/bin/perl
#
# Force connections to host via telnet to show the cps values are working
# that are set in xinetd.conf
#
# Chris Van Hoof <vanhoof@redhat.com>
#


use strict;

$|++;

use Net::Telnet;
use Benchmark;
use IO::Pipe;
use POSIX 'WNOHANG';

my $host = $ARGV[0];
my $username = $ARGV[1];
my $password = $ARGV[2]; 
my $iterations = $ARGV[3]; 
my $debug = $ARGV[4];


sub telnet_to_host {
    my $iteration = shift;
    my $number_of_times_denied = 0;
    
    my $t = new Net::Telnet (
        Timeout => 20,
        Prompt => '/\$ /'
    );

    eval('$t->open($host);');

    while ($@) {
	    $number_of_times_denied++;
	    sleep 1;
	    eval('$t->open($host);');
    }
    
    $t->login($username, $password);
    my @lines = $t->cmd("sleep 10");
    print $iteration."\t".$number_of_times_denied."\n";
}

my $pipe = IO::Pipe->new || die "Can't pipe: $!";
my $t0 = new Benchmark;
		
for (my $i = 0; $i < $iterations; $i++) {
	die "Can't fork: $!" unless defined(my $pid = fork());
	next if $pid;

	$pipe->writer; 
	select $pipe;

	telnet_to_host($i);
	exit 0;
}

$SIG{CHLD} = sub { do {} while waitpid(-1, WNOHANG) > 0; };

$pipe->reader;
while (<$pipe>) {
	print $_ if $debug;
}

my $t1 = new Benchmark;

my $td = timediff($t1, $t0);
print 	"$host - Telnet ".
	"with $iterations iterations took: ",
	timestr($td),"\n";

exit;
