#!/usr/bin/perl
#
# Copyright (C) 2009 Gustavo Noronha Silva <gns@gnome.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; see the file COPYING.LIB.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.

use strict;
use warnings;

use FindBin;
use lib $FindBin::Bin;
use webkitdirs;

# This initializes the correct configuration (Release/Debug)
setConfiguration();

my @unitTests;
my $programsDirectory = productDir() . "/Programs";
push(@unitTests, glob($programsDirectory . "/unittests/*"));
push(@unitTests, glob($programsDirectory . "/WebKit2APITests/*"));

if ($#unitTests < 1) {
    die "ERROR: tests not found in $programsDirectory.\n";
}

my $pid = fork();
if ($pid == 0) {
    close(STDOUT) or die "Can't close STDOUT: $!\n";
    close(STDERR) or die "Can't close STDERR: $!\n";
    exec("Xvfb :31 -screen 0 800x600x24 -nolisten tcp");
    exit 1;
} elsif ($pid == -1) {
    print "Failed to fork Xvfb.";
    exit 1;
}

$ENV{"DISPLAY"} = ':31';

my $exitStatus = 0;
foreach my $unitTest (@unitTests)
{
    next unless (-f $unitTest and -x $unitTest);

    system "gtester $unitTest";
    if ($?) {
        $exitStatus = $?;
    }
}

kill 9, $pid unless $pid <= 0;

if ($exitStatus) {
    print "Tests failed\n";
    exit $exitStatus;
}
