#!/usr/local/bin/perl

# Run this in the same directory as your multifinger program, as
#   perl ./test-mf.pl

# You should first run whichever of these works:
#   limit openfiles 64
#   limit descriptors 64
#   ulimit -n 64

my $goodhost = "cranium.lcs.mit.edu";
my $badhost = "frenulum.lcs.mit.edu";
my $mf = "./multifinger";

use strict;

if(! -x $mf){
    print STDERR "Where is $mf ?\n";
    exit(1);
}

my $ok = 1;
$| = 1;

print "Finger one user: ";
my $z = `$mf xyz\@$goodhost`;
if($z =~ /You fingered xyz/){
    print "passed\n";
} else {
    print "failed\n";
    $ok = 0;
}

print "Finger two users: ";
$z = `$mf abc\@$goodhost def\@$goodhost`;
if($z =~ /fingered abc/ && $z =~ /fingered def/){
    print "passed\n";
} else {
    print "failed\n";
    $ok = 0;
}

print "Time out a stuck host in 10 seconds: ";
my $t0 = time();
$z = `$mf xxx\@$badhost`;
my $t1 = time();
if($t1 - $t0 > 8 && $t1 - $t0 < 15){
    print "passed\n";
} else {
    print "failed\n";
}

print "Combination of good and stuck hosts: ";
$t0 = time();
$z = `$mf aaa\@$goodhost bbb\@$badhost ccc\@$goodhost ddd\@$badhost`;
$t1 = time();
if($z =~ /red aaa/ && $z =~ /red ccc/ &&
   $z !~ /red bbb/ && $z !~ /red ddd/ &&
   $t1 - $t0 > 8 && $t1 - $t0 < 15){
    print "passed\n";
} else {
    print "failed\n";
    $ok = 0;
}

print "More than 64 hosts: ";
my $arg = "";
my $i;
for($i = 0; $i < 80; $i++){
    $arg .= "x" . $i . "y\@" . $goodhost . " ";
}
$z = `$mf $arg`;
for($i = 0; $i < 80; $i++){
    if($z !~ /x${i}y/){
        last;
    }
}
if($i == 80){
    print "passed\n";
} else {
    print "failed\n";
    $ok = 0;
}

print "Lots of good and stuck hosts: ";
$arg = "";
for($i = 0; $i < 64; $i++){
    $arg .= "a" . $i . "y\@" . $goodhost . " ";
}
for($i = 0; $i < 64; $i++){
    $arg .= "b" . $i . "y\@" . $badhost . " ";
}
for($i = 0; $i < 64; $i++){
    $arg .= "c" . $i . "y\@" . $goodhost . " ";
}
$t0 = time();
$z = `$mf $arg`;
$t1 = time();
my $cooking = 1;
for($i = 0; $i < 64; $i++){
    if($z !~ /a${i}y/ || $z =~ /b${i}y/ || $z !~ /c${i}y/){
        $cooking = 0;
    }
}
if($cooking){
    print "passed\n";
} else {
    print "failed\n";
    $ok = 0;
}
