#!/usr/bin/perl
#
# Copyright © 1998      Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
# Copyright © 2005-2008 Ryan Murray <rmurray@debian.org>
# Copyright © 2008      Roger Leigh <rleigh@debian.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
#######################################################################

use strict;
use warnings;

use POSIX;
use Sbuild qw(isin usage_error);
use WannaBuild::Conf;
use Sbuild::Sysconfig;
use Sbuild::DB::Info;
use Sbuild::DB::MLDBM;
use Sbuild::DB::Postgres;
use WannaBuild::Database;
use WannaBuild::Options;

# global vars
$| = 1;

my $conf = WannaBuild::Conf->new();
exit 1 if !defined($conf);
my $options = WannaBuild::Options->new($conf, "wanna-build", 1);
exit 1 if !defined($options);
my $database = Wannabuild::Database->new($conf);
exit 1 if !defined($database);

# map program invocation names to operation modes
my %prognames = ( "uploaded-build"  => "set-uploaded",
		  "failed-build"    => "set-failed",
		  "no-build"		=> "set-not-for-us",
		  "give-back-build" => "set-needs-build",
		  "dep-wait-build"  => "set-dep-wait",
		  "forget-build"	=> "forget",
		  "merge-quinn"		=> "merge-quinn",
		  "merge-packages"  => "merge-packages",
		  "merge-sources"   => "merge-sources",
		  "build-info"		=> "info" );


my $progname;
($progname = $0) =~ s,.*/,,;

if ($prognames{$progname}) {
    $conf->set('DB_OPERATION', $prognames{$progname});
} elsif ($progname =~ /^list-(.*)$/) {
    $conf->set('DB_OPERATION', 'list');
    $conf->set('DB_LIST_STATE', ($1 eq "all") ? "" : $1);
}

# All logging is to standard out and error; no log stream to set.
my $status = $database->run();

exit $status;

END {
    if (defined($database)) {
	my $databases = $database->get('Databases');
	foreach (keys %{$databases}) {
	    $databases->{$_}->close();
	    undef $databases->{$_};
	}
    }
}
