#!/usr/bin/perl -w
use strict;
use Socket;
use IO::Handle;
my ($remote,$port, $iaddr, $paddr, $proto, $line);

$remote  = shift || 'localhost';
$port    = shift || 2345;  # random port
if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
die "No port" unless $port;
$iaddr   = inet_aton($remote)               || die "no host: $remote";
$paddr   = sockaddr_in($port, $iaddr);

$proto   = getprotobyname('tcp');
socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
connect(SOCK, $paddr) || die "connect: $!";
SOCK->autoflush(1);

# get first line, remove line ending
$_ = <SOCK>;
$_ =~ s/\r*\n*$//;

if (/220\s+AGSP\s+(\S+)\s+(\S+)$/) {
    print "connected to an '$1' version '$2'\n";
} else {
    die "strange server '$_', quitting";
}

# tell the server to provide scancodes
print SOCK "SCAN\r\n";

my $scans = 0;
my $errors = 0;
# loop
while (($scans < 50) && defined($line = <SOCK>)) {
    # remove line ending(s)
    $line =~ s/\r*\n*$//;
    if ($line =~ /^250 scanned ([0-9]+)$/) {
        if ($1 =~ /^978/) {
            print SOCK "ACCEPTED\r\n";
        } else {
            print SOCK "REJECTED hardcoded\r\n";
        }
        $scans++;
    } else {
        print SOCK "REJECTED whatever\r\n";
        print "From server: $line\n";
        $line = <SOCK>;
        $line =~ s/\r*\n*$//;
        print "OK from server missing on reject\n" unless ($line =~ /^211 /);
        $errors++ unless ($line =~ /^211 /);
    }
    $line = <SOCK>;
    $line =~ s/\r*\n*$//;
    print "OK from server missing on response\n" unless ($line =~ /^211 /);
    $errors++ unless ($line =~ /^211 /);
    print SOCK "SCAN\r\n" if ($scans < 50);
}

print SOCK "QUIT\r\n";
$line = <SOCK>;
$line =~ s/\r*\n*$//;
print "bye from server missing on quit\n" unless ($line =~ /^221 /);
$errors++ unless ($line =~ /^221 /);

close (SOCK) || die "close: $!";

print "$scans scans, $errors errors\n";
exit;
