#!/usr/bin/env perl
use strict;
use warnings;

my %params;
my @ARGS = ( "--force", "--no-pid" );
my $skip = 0;
my $execute = 1;
my $verbose = 0;
my $link = 0;
my $loops = 1;
my $usage =
    "usage: $0 [--loops=<n>] [--link] [--start <name>] ".
    "[-n] [/<pattern>/] [run opts]";
foreach my $n ( 0 .. $#ARGV )
{
    my $arg = $ARGV[$n];
    my $arg1 = ( $n >= $#ARGV ) ? undef : $ARGV[$n+1];
    if ( $skip > 0 ) {
	$skip--;
	next;
    }
    if ( $arg eq "--start" ) {
	if ( !defined $arg1 ) {
	    print STDERR "$usage\n";
	    exit 1;
	}
	$params{start} = $arg1;
	$skip = 1;
    }
    elsif ( $arg eq "--link" ) {
	$link = 1;
    }
    elsif ( $arg =~ /^--loops=(\d+)/ ) {
	$loops = $1;
    }
    elsif ( $arg eq "-n" or $arg eq "--no-exec" ) {
	$execute = 0;
    }
    elsif ( $arg eq "-v" or $arg eq "--verbose" ) {
	push( @ARGS, $arg );
	$verbose++;
	push( @ARGS, "-v" )
    }
    elsif ( $arg eq "-h" or $arg eq "--help" ) {
	print "$usage\n";
	exit( 0 );
    }
    elsif ( $arg eq "-h" or $arg eq "--help" ) {
	print "$usage\n";
	print "\nusage for base test script:\n";
	exec( "./lib_eventlog_rotation.pl -h" );
    }
    elsif ( $arg =~ /^\/(.*)\/$/ ) {
	$params{pat} = $1;
    }
    else {
	push( @ARGS, $arg );
    }
}

my @names =
qw (
    defaults
    no_rotations_1
    no_rotations_2
    no_rotations_3

    w_old_rotations
    w_old_rotations_2_loops
    w_2_rotations
    w_2_rotations_2_loops
    w_5_rotations
    w_20_rotations
    w_20_rotations_2_loops
    w_20_rotations_20_loops

    close_log

    reader_simple
    reader_old_rotations
    reader_old_rotations_2_loops
    reader_2_rotations
    reader_2_rotations_2_loops
    reader_20_rotations
    reader_20_rotations_2_loops
    reader_20_rotations_20_loops

    reader_missed_1
    reader_missed_2
);

my $format = "lib_eventlog_rotation-%s.run";
if ( $link )
{
    my $base = sprintf( $format, "base" );
    foreach my $name ( @names ) {
	my $test = sprintf( "lib_eventlog_rotation-%s.run", $name );
	if ( -l $test || -f $test ) {
	    unlink( $test ) or die "Can't unlink $test";
	}
	symlink( $base, $test ) or die "Can't create symlink to $test";
	print "linking: $base -> $test\n";
    }
    exit 0;
}

foreach my $loop ( 1 .. $loops ) {
    print "\n\n*** Starting testing loop $loop of $loops ***\n";
    foreach my $name ( @names ) {
	my $test = sprintf( $format, $name ) . " " . join(" ", @ARGS);
	if ( $params{start} ) {
	    if ( $name =~ /$params{start}/ ) {
		delete $params{start};
	    }
	    else {
		next;
	    }
	}
	elsif ( $params{pat} ) {
	    if ( ! ($name =~ /$params{pat}/) ) {
		next;
	    }
	}
	print "\n\n*** Running test '$name' ***\n";
	if ( $verbose ) {
	    print "Running: '$test'\n";
	}
	if ( $execute ) {
	    system( "./$test" );
	    if ( $? != 0 ) {
		print "*** Failed on test '$name' ***\n";
		print "$test\n";
		exit( $?>>8 );
	    }
	}
    }
}
print "\n\n*** All tests completed successfully ***\n";
exit 0;
