#!/usr/bin/perl -w

use Getopt::Std;

my $usage = "Usage: $0 [-p pid_file] args\n";

# locations of stuff
chomp($location = `dirname $0`);

# get the server root by popping the /bin off of our parent directory
@parts = split(/\//, $location);
pop(@parts);
my $root = join("/", @parts);

# but we're in the test directory, so we want up one
$realroot = $root;
$root = "$root/..";

my $java = "java";

# determine our machine architecture
my $ostype = `uname -s`;
my $machtype = `uname -m`;
chomp($ostype);
chomp($machtype);
my $arch = "$machtype-$ostype";

# add our native libraries to the runtime library path
my $libs = "$root/lib/$arch";
my $libpath = $ENV{"LD_LIBRARY_PATH"};

if (defined $libpath) {
    $ENV{"LD_LIBRARY_PATH"} = "$libs:$libpath";
} else {
    $ENV{"LD_LIBRARY_PATH"} = $libs;
}

# put everything in our class path
my $classpath = "-classpath $root/tests/dist/classes:$root/dist/classes";

# add zip and jar files from our lib/ directory and the global Java
# libraries directory
my @dirs = ( "$root/dist/lib" );
foreach $dir (@dirs) {
    next unless (defined $dir);
    if (opendir(DIR, $dir)) {
        foreach $lib (grep { /.(zip|jar)/ && -f "$dir/$_" } readdir(DIR)) {
            # skip nenya-*.jar because we have the nenya build directory
            # in our classpath
            $classpath .= ":$dir/$lib" unless $lib =~ /nenya/;
        }
        closedir DIR;
    }
}

# finally add the standard classes
$classpath = "$classpath";

# specify our server root (this is for server code)
my $rootarg = "-Dresource_dir=$realroot/rsrc -Dtest_dir=$realroot";

my $pid_file = undef;
my $i = 0;

# strip out the -p args (we'd use getopt() but the damned thing provides
# no way of escaping arguments so that we can pass args to runjava that
# get passed down to the JVM)
for ($i = 0; $i < @ARGV; $i++) {
    my $arg = $ARGV[$i];

    # stop when we see -- (and strip it out because Java don't dig --)
    if ($arg eq "--") {
        splice(@ARGV, $i, 1);
        last;
    }

    if ($arg eq "-p") {
        $pid_file = $ARGV[$i+1];
        splice(@ARGV, $i, 2);
	$i -= 1; # decrement i so that things stay in sync
    }
}

# log the pid file if requested to do so
print `echo $$ > $pid_file` if (defined $pid_file);

my $cmd = "$java -mx256M $classpath $rootarg " . join(" ", @ARGV);
# print "$cmd\n";
exec($cmd);
