#!/usr/bin/perl -w

use strict;

my $verbose = 0;
my $clean = 0;
while (defined $ARGV[0] && ("-v" eq $ARGV[0])) {
    $verbose++;
    shift @ARGV;
}

while (defined $ARGV[0] && ("-c" eq $ARGV[0])) {
    $clean++;
    shift @ARGV;
}

my $libs = $ENV{"LIBS"} || "";

sub mysys {
    my $cmd = shift;

    if ($verbose > 1) {
	print "$cmd\n";
    }
    return system($cmd);
}

sub runone {
    my ($t, $p, $d, $tname, $input) = @_;
    my $res;
    my $output;

    $p = "" if (!defined $p);
    $d = "" if (!defined $d);
    $tname = $t if (!defined $tname);
    $input = $t if (!defined $input);
    $output = "$input.OUTPUT";
    $input =  "$input.INPUT";

    if ($clean) {
	system "rm -rf $tname";
    }

    mkdir $tname, 0755;
    chdir $tname;
    $res = mysys("gcc $d -g -o $t ../$t.c -L../.. -lcyrus -lrt");
    if (!$res) {
	$res = mysys("./$t $p < ../$input > $t.TEMP");
	$res = mysys("cmp -s $t.TEMP ../$output");
    }
    if ($res) {
	print "$tname FAILED\n";
    } elsif ($verbose) {
	print "$tname ok\n";
    }
    chdir "..";
}

runone("cyrusdb", undef, "-DBACKEND=cyrusdb_flat -ldb ${libs}");
runone("cyrusdb", undef, "-DBACKEND=cyrusdb_skiplist -ldb ${libs}", "cyrusdb_skiplist");
runone("cyrusdb", undef, "-DBACKEND=cyrusdb_berkeley -ldb ${libs}", "cyrusdb_berkeley");

runone("cyrusdb", undef, "-DBACKEND=cyrusdb_flat -ldb ${libs}", 
       "cyrusdbtxn_flat", "cyrusdbtxn");
runone("cyrusdb", undef, "-DBACKEND=cyrusdb_skiplist -ldb ${libs}", 
       "cyrusdbtxn_skiplist", "cyrusdbtxn");
runone("cyrusdb", undef, "-DBACKEND=cyrusdb_berkeley -ldb ${libs}", 
       "cyrusdbtxn_berkeley", "cyrusdbtxn");

runone("cyrusdb", undef, "-DBACKEND=cyrusdb_flat -ldb ${libs}", 
       "cyrusdblong_flat", "cyrusdblong");
runone("cyrusdb", undef, "-DBACKEND=cyrusdb_skiplist -ldb ${libs}", 
       "cyrusdblong_skiplist", "cyrusdblong");
runone("cyrusdb", undef, "-DBACKEND=cyrusdb_berkeley -ldb ${libs}", 
       "cyrusdblong_berkeley", "cyrusdblong");

runone("rnddb", undef, "-DBACKEND=cyrusdb_skiplist -ldb ${libs}",
       "rndskip", "rnddb");
