#!/usr/bin/perl
#
# This program runs all test that starts with 'test-' and sums
# the results that the program prints.
# Each time result should be of the form:
# Time for|to KEYWORD 'other info': timestr()
#
# All options to this script is passed to all test program.
# useful options:
# --host=#  --db=# --fast --force --lock-tables
#
# When running with MySQL 3.20, one should use the switch --skip-in

$version="1.1";
$prog_count=$errors=0; push(@ARGV,"--skip-in");
$output="output";

$|=1;				# Output data immediately

$prog_args=join(" ",@ARGV) . " --skip-in";

if (! -d $output)
{
  if (-e $output)
  {
    die "$output isn't a directory\n";
  }
  mkdir $output,0777 || die "Can't create directory: $output\n";
}

print "Benchmark suit: $version\n";
print "Running tests on: ";
system("uname -a");
print "Arguments:        " . join(" ",@ARGV) . "\n";
system("mysqladmin ver | grep Server");
print "\n";

while (<test-*>)
{
  next if (/\.sh$/);		# configure script
  $prog_count++;
  $prog=$_;
  print "$prog: ";
  system("./$prog $prog_args > output/$prog.res 2>&1") &&
    die "Can't execute $prog.  Check the '$output' directory\n";
  open(TEST,"tail -1 output/$prog.res|");
  $last_line= <TEST>;
  if ($last_line =~ /^Total time: /)
  {
    print $last_line;
    open(TEST,"output/$prog.res");
    while (<TEST>)
    {
      if (/^Time (to|for) ([^\s:]*)[^:]*:\s*(\d*) secs \(\s*([^\s]*) usr\s*([^\s]*) sys[^\d]*([^\s]*) cpu/)
      {
	$arg=$summa{$2};
	if (!defined($arg))
	{
	  $summa{$2}= [ $3,$4,$5,$6];
	}
	else
	{
	  $arg->[0]+=$3;
	  $arg->[1]+=$4;
	  $arg->[2]+=$5;
	  $arg->[3]+=$6;
	}
      }
    }
  }
  else
  {
    $errors++;
    print "Failed\n";
  }
}

print "\n";
if (!$errors)
{
  print "All $prog_count test executed successfully\n";
}
else
{
  print "Of $prog_count tests, $errors tests didn't work\n";
}

if (%summa)
{
  @total=(0,0,0,0);
  print "\nTotals per operation:\n";
  print "Operation                secs      usr     sys     cpu\n";
  foreach $key (sort(keys %summa))
  {
    $arg=$summa{$key};
    printf("%-21.21s %7d  %7.2f %7.2f %7.2f\n",
	   $key,$arg->[0],$arg->[1],$arg->[2],$arg->[3]);
    for ($i=0 ; $i < 4 ; $i++)
    {
      $total[$i]+=$arg->[$i];
    }
  }
  printf("%-20.20s %7d  %7.2f %7.2f %7.2f\n", 
	 "TOTAL TIME",$total[0],$total[1],$total[2],$total[3]);
}
