#! /usr/bin/env perl
#testreq: personal
##**************************************************************
##
## Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
## University of Wisconsin-Madison, WI.
##
## Licensed under the Apache License, Version 2.0 (the "License"); you
## may not use this file except in compliance with the License.  You may
## obtain a copy of the License at
##
##    http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
##**************************************************************

use strict;
use warnings;
use Cwd;

sub usage( )
{
    print
	"usage: $0 [options]\n" .
	"  -n|--no-exec  no execute / test mode\n" .
	"  -v|--verbose  increase verbose level\n" .
	"  -d|--debug    enable D_FULLDEBUG debugging\n" .
	"  -q|--quiet    cancel debug & verbose\n" .
	"  -h|--help     this help\n";
}


my %settings =
(
 verbose	=> 0,
 debug		=> 0,
 execute	=> 1,
 stop		=> 0,
 build_mode	=> 0,
 name		=> "base",
 );

# if _build, for --build mode
if ( $0 =~ /_build/ )
{
    push( @ARGV, "--build" );
}

foreach my $arg ( @ARGV ) {
    if ( $arg eq "-b"  or  $arg eq "--build" ) {
	$settings{build_mode} = 1;
	$settings{name} = "build";
    }
    elsif ( $arg eq "-n"  or  $arg eq "--no-exec" ) {
	$settings{execute} = 0;
    }
    elsif ( $arg eq "-v"  or  $arg eq "--verbose" ) {
	$settings{verbose}++;
    }
    elsif ( $arg eq "-d"  or  $arg eq "--debug" ) {
	$settings{debug} = 1;
    }
    elsif ( $arg eq "-q"  or  $arg eq "--quiet" ) {
	$settings{verbose} = 0;
	$settings{debug} = 0;
    }
    elsif ( $arg eq "-h"  or  $arg eq "--help" ) {
	usage( );
	exit(0);
    }
    else {
	print STDERR "Unknown argument $arg\n";
	usage( );
	exit(1);
    }
}

my $dir = "test-eventlog_" . $settings{name};
my $exe = "./lib_eventlog_".$settings{name}."_executable.exe";
my $fulldir = getcwd() . "/$dir";
unlink "$dir/EventLog";
unlink "$dir/reader.state";
rmdir $dir;

mkdir( $dir ) or die "Can't create directory $dir";
print "writing to $dir\n" if ( $settings{verbose} );

sub run( @ );

# Build it
if ( $settings{build_mode} )
{
	unlink $exe;
    my @args = ( "make", $exe );
    my $r = run( @args );
    exit( $r ) if ( $r );
}

# Test it
my @args = ( $exe, "$dir/EventLog", "$dir/reader.state" );
my $r = run( @args );
exit( $r ) if ( $r );

exit(0);

# Run program
sub run( @ )
{
    print "Running: " . join(" ", @_) . "\n";

    if ( $settings{execute} )
    {
	my $status = system( @_ );
	if ( $status < 0 )
	{
	    die "Failed to execute " . join(" ", @_) . ": $?";
	}
    }

    return( $? >> 8 );
}
