#!/usr/bin/perl -w

use Getopt::Std;
use FileHandle;

autoflush STDOUT 1;

getopts('hdt:n:s:p:b:e:');

if ($opt_h) {
    print "$0: \n";
    print "\t-p program\n";
    print "\t-d (don't remount)\n";
    print "\t-t number of times to run each test\n";
    print "\t-b read size (block size)\n";
    print "\t-s number of streams\n";
    print "\t-e errors to stop at\n";
    print "\t-n number of blocks to read per test\n";
    print "\t-h (print help)\n";
    exit(1);
}

$binary = $opt_p || "./rrfiles";
$number = $opt_t || 10;
$size = $opt_b || 1024;
$threads = $opt_s || 15;
$allow_errors = $opt_e || 100;
$num_blocks = $opt_n || 100;
$dontmount = $opt_d;

if($dontmount) {
    print "Yup.\n";
}

$opt_p = $opt_t = $opt_s = $opt_b = $opt_e = $opt_n = $opt_h = $opt_d = "";

print "Beginning test run with binary $binary, $number tests per ";
print "thread, $size"."Kb \n size blocks, and beginning at $threads threads.\n";

sub docmd {
    my($cmd) = @_;
    my($rv);
    print "$cmd\n";
    print `$cmd`;
    $rv = ($? >> 8);
    if($rv > 0) {
	die "Non zero exit status ($rv, $?) from command: \n$cmd\n$!";
    }
}

$nthreads = $threads;

THREAD: while(1) {
	my($failures)= 0;
    TEST: for(1..$number) {
		docmd("sync");
		# print "umounting...",`umount $mountpoint`;
		# docmd("mount $dev $mountpoint");
		docmd("fs_remount") unless ($dontmount);
		print `fs_unmount` if($dontmount);

		print "Running test...\n";
		$cmd = "$binary -b $size -s $nthreads -n $num_blocks";
		print "$cmd\n";
		$result = `$cmd`;
		print $result;
		if($result =~ /Total errors: (\d+)/) {
		    $errors = $1;
		} else {
		    die "Can't get total errors from output.";
		}
		$failures += $errors;
	}

	++$nthreads;

	print "Results: $binary\t$size\t$nthreads\t$number\t$failures\n";
	if($failures >= $allow_errors*$number) {
		last THREAD;
	}
}




