#!/usr/bin/perl -w

use strict;

use IO::Socket;

my($opt_p,$opt_s,$opt_e);
my($socket, $response);
my (@detail, @failures);

use Getopt::Long;
Getopt::Long::Configure("bundling");

GetOptions("p=i" => \$opt_p, "port=i" => \$opt_p,
	   "s=s" => \$opt_s, "send=s" => \$opt_s,
           "e=s" => \$opt_e, "expect=s" => \$opt_e,);

foreach my $host (@ARGV) {
    $socket = IO::Socket::INET->new(Proto=>"tcp",PeerAddr=>$host,PeerPort=>"$opt_p");
    if ($socket) 
    {
	if ($opt_s) { $socket->print(eval(qq/"$opt_s"/)); }
	if ($opt_e) {
	    $response = join '', $socket->getlines();
	    if (!($response =~ /$opt_e/m)) {
		push @failures, $host;
		push @detail, "$host: Didn't match $opt_e\n";
	    } else {
		push @detail, "$host: $&\n";
	    }
	} else {
	    $response = $socket->getline();
            if ($response) {
	        chomp $response;
		push @detail, "$host: $response\n";
	    } else {
		push @detail, "$host: No output\n";
	    }
	}
    } else {
	push @failures, $host;
	push @detail, "$host: $@\n";
    }
    $socket->close() if $socket;
}

print join(' ',@failures),"\n";
print join('',@detail);
exit 1 if @failures;
exit 0;
