]> git.donarmstrong.com Git - wannabuild.git/blob - bin/wanna-build
merge-v3: fix moving binNMUed packages to installed
[wannabuild.git] / bin / wanna-build
1 #!/usr/bin/perl
2
3 # wanna-build: coordination script for Debian buildds
4 # Copyright (C) 1998 Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
5 # Copyright (C) 2005-2008 Ryan Murray <rmurray@debian.org>
6 # Copyright (C) 2010      Andreas Barth <aba@not.so.argh.org>
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; either version 2 of the
11 # License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21 #
22 use strict;
23 use warnings;
24 use 5.010;
25
26 package conf;
27
28 use vars qw< $basedir $dbbase $transactlog $mailprog $buildd_domain >;
29 # defaults
30 $basedir ||= "/var/lib/debbuild";
31 $dbbase ||= "build-db";
32 $transactlog ||= "transactions.log";
33 $mailprog ||= "/usr/sbin/sendmail";
34 require "/org/wanna-build/etc/wanna-build.conf";
35 die "$conf::basedir is not a directory\n" if ! -d $conf::basedir;
36 die "dbbase is empty\n" if ! $dbbase;
37 die "transactlog is empty\n" if ! $transactlog;
38 die "mailprog binary $conf::mailprog does not exist or isn't executable\n"
39         if !-x $conf::mailprog;
40 package main;
41
42 use POSIX;
43 use FileHandle;
44 use File::Copy;
45 use DBI;
46 use lib '/org/wanna-build/lib';
47 #use lib 'lib';
48 use WannaBuild;
49 use YAML::Tiny;
50 use Data::Dumper;
51 use Hash::Merge qw ( merge );
52 use String::Format;
53 use Date::Parse;
54 use List::Util qw[max];
55 use Dpkg::Version (); # import nothing
56 if ( defined $Dpkg::Version::VERSION ) {
57     *vercmp = \&Dpkg::Version::version_compare;
58 } else {
59     *vercmp = \&Dpkg::Version::vercmp;
60 }
61
62 use Dpkg::Deps; # TODO: same
63
64 our ($verbose, $mail_logs, $list_order, $list_state,
65     $curr_date, $op_mode, $user, $real_user, $distribution,
66     $fail_reason, $opt_override, $import_from, $export_to, $opt_create_db,
67     %prioval, %sectval,
68     $info_all_dists, $arch,
69     $category, %catval, %short_category,
70     $short_date, $list_min_age, $dbbase, @curr_time,
71     $build_priority, %new_vers, $binNMUver, %merge_srcvers, %merge_binsrc,
72     $printformat, $ownprintformat, $privmode, $extra_depends, $extra_conflicts,
73     %distributions, %distribution_aliases
74     );
75 our $Pas = '/org/buildd.debian.org/etc/packages-arch-specific/Packages-arch-specific';
76 our $simulate = 0;
77 our $simulate_edos = 0;
78 our $api = undef; # allow buildds to specify an different api
79 our $recorduser = undef;
80
81 # global vars
82 $ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin:/org/wanna-build/bin/";
83 $ENV{'LC_ALL'} = 'C';
84 $verbose = 0;
85 $mail_logs = "";
86 @curr_time = gmtime;
87 $curr_date = strftime("%Y %b %d %H:%M:%S",@curr_time);
88 $short_date = strftime("%m/%d/%y",@curr_time);
89 $| = 1;
90
91 # map program invocation names to operation modes
92 my %prognames = ( "uploaded-build"  => "set-uploaded",
93                                   "failed-build"    => "set-failed",
94                                   "no-build"            => "set-not-for-us",
95                                   "give-back-build" => "set-needs-build",
96                                   "dep-wait-build"  => "set-dep-wait",
97                                   "forget-build"        => "forget",
98                                   "build-info"          => "info" );
99
100 %short_category = ( u => "uploaded-fixed-pkg",
101                                     f => "fix-expected",
102                                         r => "reminder-sent",
103                                         n => "nmu-offered",
104                                         e => "easy",
105                                         m => "medium",
106                                         h => "hard",
107                                         c => "compiler-error",
108                                         "" => "none" );
109
110 my $progname;
111 ($progname = $0) =~ s,.*/,,;
112 if ($prognames{$progname}) {
113         $op_mode = $prognames{$progname};
114 }
115 elsif ($progname =~ /^list-(.*)$/) {
116         $op_mode = "list";
117         $list_state = ($1 eq "all") ? "" : $1;
118 }
119
120 my %options =
121         (# flags
122          simulate       => { flag => \$simulate }, # this is not supported by all operations (yet)!
123          "simulate-edos"  => { flag => \$simulate_edos },
124          "simulate-all" => { code => sub { $simulate = 1; $simulate_edos = 1; } },
125          api            => { arg => \$api, code => sub {
126                             # official apis are numeric
127                             die "$api isn't numeric" unless int($api) eq $api;
128                             die "$api too large" unless $api <= 1;
129                             } },
130          verbose        => { short => "v", flag => \$verbose },
131          override               => { short => "o", flag => \$opt_override },
132          "create-db"    => { flag => \$opt_create_db },
133          "correct-compare" => { flag => \$WannaBuild::opt_correct_version_cmp },
134          # TODO: remove after buildds no longer pass to wanna-build
135          "no-propagation" => { short => "N" },
136          "no-down-propagation" => { short => "D" },
137          # normal actions
138          take                   => { mode => "set-building" },
139          failed                 => { short => "f", mode => "set-failed" },
140          uploaded               => { short => "u", mode => "set-uploaded" },
141          "no-build"             => { short => "n", mode => "set-not-for-us" },
142          built                  => { mode => "set-built" },
143          attempted              => { mode => "set-attempted" },
144          "give-back"            => { mode => "set-needs-build" },
145          "dep-wait"             => { mode => "set-dep-wait" },
146          forget                 => { mode => "forget" },
147          'forget-user' => { mode => 'forget-user' },
148          update                 => { mode => "set-update" },
149          "merge-v3"      => { mode => "merge-v3" },
150          info                   => { short => "i", mode => "info" },
151          'binNMU' => { mode => 'set-binary-nmu', arg => \$binNMUver, 
152                              code => sub { die "Invalid binNMU version: $binNMUver\n"
153                                 if $binNMUver !~ /^([\d]*)$/ and $1 >= 0; } },
154          'perm-build-priority'    => { mode => "set-permanent-build-priority", arg => \$build_priority,
155                               code => sub { die "Invalid build priority: $build_priority\n"
156                                 if $build_priority !~ /^-?[\d]+$/; } },
157          'build-priority'    => { mode => "set-build-priority", arg => \$build_priority,
158                               code => sub { die "Invalid build priority: $build_priority\n"
159                                 if $build_priority !~ /^-?[\d]+$/; } },
160          list                   =>
161          { short => "l", mode => "list", arg => \$list_state,
162            code => sub {
163                    die "Unknown state to list: $list_state\n"
164                            if !isin( $list_state, qw(needs-build building uploaded
165                                                  built build-attempted failed installed dep-wait
166                                                  not-for-us auto-not-for-us all failed-removed
167                                                  install-wait reupload-wait bd-uninstallable));} },
168          # options with args
169          dist           =>
170          { short => "d", arg => \$distribution,
171            code => sub {
172                    if ($distribution eq "a" || $distribution eq "all") {
173                            $info_all_dists = 1;
174                            $distribution = "";
175                    }
176                    else {
177                            $distribution = "oldstable"   if $distribution eq "o";
178                            $distribution = "stable"   if $distribution eq "s";
179                            $distribution = "testing"  if $distribution eq "t";
180                            $distribution = "unstable" if $distribution eq "u";
181                    }
182            } },
183          order          =>
184          { short => "O", arg => \$list_order,
185            code => sub {
186                    die "Bad ordering character\n"
187                            if $list_order !~ /^[PSpsncbCWT]+$/;
188            } },
189          message        => { short => "m", arg => \$fail_reason },
190          # database is deprecated, use arch instead.
191          database       => { short => "b", arg => \$conf::dbbase },
192          arch           => { short => "A", arg => \$arch },
193          user           => { short => "U", arg => \$user },
194          category               => { short => "c", arg => \$category,
195                                                  code => sub {
196                                                          $category = $short_category{$category}
197                                                                  if exists $short_category{$category};
198                                                          die "Unknown category: $category\n"
199                                                                  if !isin( $category, values %short_category );
200                                                  } },
201          "min-age"      => { short => "a", arg => \$list_min_age,
202                                                  code => sub {
203                                                          die "Argument of --min-age must be a non-zero number\n"
204                                                                  if $list_min_age == 0;
205                                                  } },
206          "max-age"      => { arg => \$list_min_age,
207                                                  code => sub {
208                                                          die "Argument of --max-age must be a non-zero number\n"
209                                                                  if $list_min_age == 0;
210                                                          $list_min_age *= -1;
211                                                  } },
212          "format"       => { arg => \$printformat },
213          "own-format"       => { arg => \$ownprintformat },
214          "Pas"          => { arg => \$Pas },
215          "extra-depends"=> { arg => \$extra_depends },
216          "extra-conflicts"=> { arg => \$extra_conflicts },
217          # special actions
218          export         => { arg => \$export_to, mode => "export" },
219          import         => { arg => \$import_from, mode => "import" },
220          "manual-edit"  => { mode => "manual-edit" },
221          "distribution-architectures" => { mode => "distribution-architectures" },
222          "distribution-aliases" => { mode => "distribution-aliases" },
223          );
224
225 while( @ARGV && $ARGV[0] =~ /^-/ ) {
226         $_ = shift @ARGV;
227         last if $_ eq "--";
228         my($opt, $optname, $arg);
229         if (/^--([^=]+)(=|$)/) {
230                 $optname = $1;
231                 $opt = $options{$optname};
232                 $arg = $1 if /^--\Q$optname\E=((.|\n)*)$/;
233         }
234         else {
235                 $optname = substr( $_, 1, 1 );
236                 $opt = (grep { defined($_->{short}) ? $_->{short} eq $optname : 0} values %options)[0];
237                 $arg = $1 if /^-$optname(.+)$/;
238         }
239         if (!$opt) {
240                 warn "Unknown option: --$1\n";
241                 usage();
242         }
243         if ($opt->{arg}) {
244                 if (!defined $arg) {
245                         die "$optname option missing argument\n" if !@ARGV;
246                         $arg = shift @ARGV;
247                 }
248                 ${$opt->{arg}} = $arg;
249         }
250         elsif (defined $arg) {
251                 die "Option $optname takes no argument\n";
252         }
253         
254         if ($opt->{mode}) {
255                 die "Conflicting operation modes\n" if $op_mode;
256                 $op_mode = $opt->{mode};
257         }
258         if ($opt->{flag}) {
259                 ${$opt->{flag}}++;
260         }
261         if ($opt->{code}) {
262                 &{$opt->{code}};
263         }
264 }
265
266 my $dbh;
267
268 END {
269         if (defined $dbh)
270         {
271                 $dbh->disconnect or warn $dbh->errstr;
272         }
273 }
274
275 $distribution ||= "sid";
276 if ($distribution eq 'any-priv') {
277     $privmode = 1;
278     $distribution = 'any';
279 }
280 if ($distribution eq 'any-unpriv') {
281     $privmode = 0;
282     $distribution = 'any';
283 }
284
285 my $schema_suffix = '';
286 $recorduser //= (not -t and $user//"" =~ /^buildd_/);
287 if ((isin( $op_mode, qw(list info)) && $distribution !~ /security/ && !$recorduser && !($privmode)) || $simulate) {
288         $dbh = DBI->connect("DBI:Pg:service=wanna-build") || 
289                 die "FATAL: Cannot open database: $DBI::errstr\n";
290         $schema_suffix = '_public';
291 }
292 else
293 {
294         $dbh = DBI->connect("DBI:Pg:service=wanna-build-privileged") || 
295                 die "FATAL: Cannot open database: $DBI::errstr\n";
296 }
297
298 # TODO: This shouldn't be needed, file a bug.
299 $dbh->{pg_server_prepare} = 0;
300
301 $dbh->begin_work or die $dbh->errstr;
302
303 my $q = 'SELECT distribution, public, auto_dep_wait, build_dep_resolver, suppress_successful_logs, archive FROM distributions';
304 my $rows = $dbh->selectall_hashref($q, 'distribution');
305 foreach my $name (keys %$rows) {
306         $distributions{$name} = {};
307         $distributions{$name}->{'noadw'} = 1 if !($rows->{$name}->{'auto_dep_wait'});
308         $distributions{$name}->{'hidden'} = 1 if !($rows->{$name}->{'public'});
309         $distributions{$name}->{'build_dep_resolver'} = $rows->{$name}->{'build_dep_resolver'} if $rows->{$name}->{'build_dep_resolver'};
310         $distributions{$name}->{'suppress_successful_logs'} = $rows->{$name}->{'suppress_successful_logs'} if $rows->{$name}->{'suppress_successful_logs'};
311         $distributions{$name}->{'archive'} = $rows->{$name}->{'archive'} if $rows->{$name}->{'archive'};
312 }
313
314 $q = 'SELECT alias, distribution FROM distribution_aliases';
315 $rows = $dbh->selectall_hashref($q, 'alias');
316 foreach my $name (keys %$rows) {
317         $distribution_aliases{$name} = $rows->{$name}->{'distribution'};
318 }
319 $distribution = $distribution_aliases{$distribution} if (isin($distribution, keys %distribution_aliases));
320
321 $op_mode = $category ? "set-failed" : "set-building"
322         if !$op_mode; # default operation
323 undef $distribution if $distribution eq 'any';
324 if ($distribution) {
325     my @dists = split(/[, ]+/, $distribution);
326     foreach my $dist (@dists) {
327         die "Bad distribution '$distribution'\n"
328             if !isin($dist, keys %distributions);
329     }
330 }
331 if (!isin ( $op_mode, qw(list) ) && ( !$distribution || $distribution =~ /[ ,]/)) {
332     die "multiple distributions are only allowed for list";
333 }
334
335 # If they didn't specify an arch, try to get it from database name which
336 # is in the form of $arch/build-db
337 # This is for backwards compatibity with older versions that didn't
338 # specify the arch yet.
339 $conf::dbbase =~ m#^([^/]+)#;
340 $arch ||= $1;
341
342 # TODO: Check that it's an known arch (for that dist), and give
343 # a proper error.
344
345 if ($verbose) {
346         my $version = '$Revision: db181a534e9d $ $Date: 2008/03/26 06:20:22 $ $Author: rmurray $';
347         $version =~ s/(^\$| \$ .*$)//g;
348         print "wanna-build $version for $distribution on $arch\n";
349 }
350
351 if (!@ARGV && !isin( $op_mode, qw(list merge-quinn merge-partial-quinn import export
352                                   merge-packages manual-edit
353                                   merge-sources distribution-architectures
354                                   distribution-aliases))) {
355         warn "No packages given.\n";
356         usage();
357 }
358
359 $real_user = (getpwuid($<))[0];
360 die "Can't determine your user name\n"
361         if $op_mode ne "list" && !$user &&
362            !($user = $real_user);
363
364 if (!$fail_reason) {
365         if ($op_mode eq "set-failed" && !$category) {
366                 print "Enter reason for failing (end with '.' alone on ".
367                       "its line):\n";
368                 my $line;
369                 while(!eof(STDIN)) {
370                         $line = <STDIN>;
371                         last if $line eq ".\n";
372                         $fail_reason .= $line;
373                 }
374                 chomp( $fail_reason );
375         } elsif ($op_mode eq "set-dep-wait") {
376                 print "Enter dependencies (one line):\n";
377                 my $line;
378                 while( !$line && !eof(STDIN) ) {
379                         chomp( $line = <STDIN> );
380                 }
381                 die "No dependencies given\n" if !$line;
382                 $fail_reason = $line;
383         } elsif ($op_mode eq "set-binary-nmu" and $binNMUver > 0) {
384                 print "Enter changelog entry (one line):\n";
385                 my $line;
386                 while( !$line && !eof(STDIN) ) {
387                         chomp( $line = <STDIN> );
388                 }
389                 die "No changelog entry given\n" if !$line;
390                 $fail_reason = $line;
391         }
392 }
393
394 my $yamlmap = ();
395 my $yamldir = "/org/wanna-build/etc/yaml";
396 my @files = ('wanna-build.yaml');
397 if ((getpwuid($>))[7]) { push (@files, ((getpwuid($>))[7])."/.wanna-build.yaml"); }
398 if ($user && $user =~ /(buildd.*)-/) { push (@files, "$1.yaml") };
399 if ($user) { push ( @files, "$user.yaml"); }
400 foreach my $file (@files) {
401         my $cfile = File::Spec->rel2abs( $file, $yamldir );
402         if ($verbose >= 2) { print "Trying to read $file ($cfile) ...\n"; }
403         next unless -f $cfile;
404         if ($verbose >= 2) { print "Read $file ($cfile) ...\n"; }
405         my $m = YAML::Tiny->read( $cfile )->[0];
406         $yamlmap = merge($m, $yamlmap);
407 }
408 if (not $yamlmap) {
409         die "FATAL: no configuration found\n";
410 }
411 $list_order = $yamlmap->{"list-order"}{$list_state} if !$list_order and $list_state;
412 $list_order ||= $yamlmap->{"list-order"}{'default'};
413 $api //= $yamlmap->{"api"};
414 $api //= 0;
415
416 process();
417
418 $dbh->commit;
419 $dbh->disconnect;
420
421 if ($mail_logs && $conf::log_mail) {
422         send_mail( $conf::log_mail,
423                            "wanna-build $distribution state changes $curr_date",
424                            "State changes at $curr_date for distribution ".
425                            "$distribution:\n\n$mail_logs\n" );
426 }
427
428 exit 0;
429
430
431 sub process {
432
433         SWITCH: foreach ($op_mode) {
434                 /^set-(.+)/ && do {
435                         add_packages( $1, @ARGV );
436                         last SWITCH;
437                 };
438                 /^list/ && do {
439                         list_packages( $list_state );
440                         last SWITCH;
441                 };
442                 /^info/ && do {
443                         info_packages( @ARGV );
444                         last SWITCH;
445                 };
446                 /^forget-user/ && do {
447                         die "This operation is restricted to admin users\n"
448                                 if (defined @conf::admin_users and
449                                     !isin( $real_user, @conf::admin_users));
450                         forget_users( @ARGV );
451                         last SWITCH;
452                 };
453                 /^forget/ && do {
454                         forget_packages( @ARGV );
455                         last SWITCH;
456                 };
457                 /^merge-v3/ && do {
458                         die "This operation is restricted to admin users\n"
459                             if (defined @conf::admin_users and !isin( $real_user, @conf::admin_users) and !$simulate);
460                         # call with installed-packages+ . installed-sources+ [ . available-for-build-packages* [ . consider-as-installed-source* ]  ]
461                         # in case available-for-build-packages is not specified, installed-packages are used
462                         lock_table() unless $simulate;
463                         my $replacemap = { '%ARCH%' => $arch, '%SUITE%' => $distribution };
464                         map { my $k = $_; grep { $k =~ s,$_,$replacemap->{$_}, } keys %{$replacemap}; $_ = $k; } @ARGV;
465                         my @ipkgs = &parse_argv( \@ARGV, '.');
466                         my @isrcs = &parse_argv( \@ARGV, '.');
467                         my @bpkgs = &parse_argv( \@ARGV, '.');
468                         my @psrcs = &parse_argv( \@ARGV, '.');
469                         use WB::QD;
470                         my $srcs = WB::QD::readsourcebins($arch, $Pas, \@isrcs, \@ipkgs);
471                         if (@psrcs) {
472                             my $psrcs = WB::QD::readsourcebins($arch, $Pas, \@psrcs, []);
473                             foreach my $k (keys %$$psrcs) {
474                                 next if $$srcs->{$k};
475                                 my $pkg = $$psrcs->{$k};
476                                 $pkg->{'status'} = 'related';
477                                 $$srcs->{$k} = $pkg;
478                             }
479                         }
480                         parse_all_v3($$srcs, {'arch' => $arch, 'suite' => $distribution, 'time' => $curr_date});
481                         @bpkgs = @ipkgs unless @bpkgs;
482                         call_edos_depcheck( {'arch' => $arch, 'pkgs' => \@bpkgs, 'srcs' => $$srcs, 'depwait' => 1 });
483                         last SWITCH;
484                 };
485                 /^import/ && do {
486                         die "This operation is restricted to admin users\n"
487                                 if (defined @conf::admin_users and
488                                     !isin( $real_user, @conf::admin_users));
489                         $dbh->do("DELETE from " . table_name() . 
490                                 " WHERE distribution = ?", undef,
491                                 $distribution)
492                                 or die $dbh->errstr;
493                         forget_users();
494                         read_db( $import_from );
495                         last SWITCH;
496                 };
497                 /^export/ && do {
498                         export_db( $export_to );
499                         last SWITCH;
500                 };
501                 /^distribution-architectures/ && do {
502                         show_distribution_architectures();
503                         last SWITCH;
504                 };
505                 /^distribution-aliases/ && do {
506                         show_distribution_aliases();
507                         last SWITCH;
508                 };
509
510                 die "Unexpected operation mode $op_mode\n";
511         }
512         if ($recorduser) {
513                 my $userinfo = get_user_info($user);
514                 if (!defined $userinfo)
515                 {
516                         add_user_info($user);
517                 }
518                 else
519                 {
520                         update_user_info($user);
521                 }
522         }
523 }
524
525 sub add_packages {
526         my $newstate = shift;
527         my( $package, $name, $version, $ok, $reason );
528         
529         foreach $package (@_) {
530                 $package =~ s,^.*/,,; # strip path
531                 $package =~ s/\.(dsc|diff\.gz|tar\.gz|deb)$//; # strip extension
532                 $package =~ s/_[a-zA-Z\d-]+\.changes$//; # strip extension
533                 if ($package =~ /^([\w\d.+-]+)_([\w\d:.+~-]+)/) {
534                         ($name,$version) = ($1,$2);
535                 }
536                 else {
537                         warn "$package: can't extract package name and version ".
538                                  "(bad format)\n";
539                         next;
540                 }
541
542                 if ($op_mode eq "set-building") {
543                         add_one_building( $name, $version );
544                 }
545                 elsif ($op_mode eq "set-built") {
546                         add_one_built( $name, $version );
547                 }
548                 elsif ($op_mode eq "set-attempted") {
549                         add_one_attempted( $name, $version );
550                 }
551                 elsif ($op_mode eq "set-uploaded") {
552                         add_one_uploaded( $name, $version );
553                 }
554                 elsif ($op_mode eq "set-failed") {
555                         add_one_failed( $name, $version );
556                 }
557                 elsif ($op_mode eq "set-not-for-us") {
558                         add_one_notforus( $name, $version );
559                 }
560                 elsif ($op_mode eq "set-needs-build") {
561                         add_one_needsbuild( $name, $version );
562                 }
563                 elsif ($op_mode eq "set-dep-wait") {
564                         add_one_depwait( $name, $version );
565                 }
566                 elsif ($op_mode eq "set-build-priority") {
567                         set_one_buildpri( $name, $version, 'buildpri' );
568                 }
569                 elsif ($op_mode eq "set-permanent-build-priority") {
570                         set_one_buildpri( $name, $version, 'permbuildpri' );
571                 }
572                 elsif ($op_mode eq "set-binary-nmu") {
573                         set_one_binnmu( $name, $version );
574                 }
575                 elsif ($op_mode eq "set-update") {
576                         set_one_update( $name, $version );
577                 }
578         }
579 }
580
581 sub add_one_building {
582         my $name = shift;
583         my $version = shift;
584         my( $ok, $reason );
585
586         $ok = 1;
587         my $pkg = get_source_info($name);
588         if (defined($pkg)) {
589                 if ($pkg->{'state'} eq "Not-For-Us") {
590                         $ok = 0;
591                         $reason = "not suitable for this architecture";
592                 }
593                 elsif ($pkg->{'state'} =~ /^Dep-Wait/) {
594                         $ok = 0;
595                         $reason = "not all source dependencies available yet";
596                 }
597                 elsif ($pkg->{'state'} =~ /^BD-Uninstallable/) {
598                         $ok = 0;
599                         $reason = "source dependencies are not installable";
600                 }
601                 elsif ($pkg->{'state'} eq "Uploaded" &&
602                            (version_lesseq($version, $pkg->{'version'}))) {
603                         $ok = 0;
604                         $reason = "already uploaded by $pkg->{'builder'}";
605                         $reason .= " (in newer version $pkg->{'version'})"
606                                 if !version_eq($pkg, $version);
607                 }
608                 elsif ($pkg->{'state'} eq "Installed" &&
609                            version_less($version,$pkg->{'version'})) {
610                         if ($opt_override) {
611                                 print "$name: Warning: newer version $pkg->{'version'} ".
612                                           "already installed, but overridden.\n";
613                         }
614                         else {
615                                 $ok = 0;
616                                 $reason = "newer version $pkg->{'version'} already in ".
617                                                   "archive; doesn't need rebuilding";
618                                 print "$name: Note: If the following is due to an epoch ",
619                                           " change, use --override\n";
620                         }
621                 }
622                 elsif ($pkg->{'state'} eq "Installed" &&
623                            pkg_version_eq($pkg,$version)) {
624                         $ok = 0;
625                         $reason = "is up-to-date in the archive; doesn't need rebuilding";
626                 }
627                 elsif ($pkg->{'state'} eq "Needs-Build" &&
628                            version_less($version,$pkg->{'version'})) {
629                         if ($opt_override) {
630                                 print "$name: Warning: newer version $pkg->{'version'} ".
631                                           "needs building, but overridden.";
632                         }
633                         else {
634                                 $ok = 0;
635                                 $reason = "newer version $pkg->{'version'} needs building, ".
636                                                   "not $version";
637                         }
638                 }
639                 elsif (isin($pkg->{'state'},qw(Building Built Build-Attempted))) {
640                         if (version_less($pkg->{'version'},$version)) {
641                                 print "$name: Warning: Older version $pkg->{'version'} ",
642                                       "is being built by $pkg->{'builder'}\n";
643                                 if ($pkg->{'builder'} ne $user) {
644                                         send_mail( $pkg->{'builder'},
645                                                            "package takeover in newer version",
646                                                            "You are building package '$name' in ".
647                                                            "version $version\n".
648                                                            "(as far as I'm informed).\n".
649                                                            "$user now has taken the newer ".
650                                                            "version $version for building.".
651                                                            "You can abort the build if you like.\n" );
652                                 }
653                         }
654                         else {
655                                 if ($opt_override) {
656                                         print "User $pkg->{'builder'} had already ",
657                                               "taken the following package,\n",
658                                                   "but overriding this as you request:\n";
659                                         send_mail( $pkg->{'builder'}, "package takeover",
660                                                            "The package '$name' (version $version) that ".
661                                                            "was taken by you\n".
662                                                            "has been taken over by $user\n" );
663                                 }
664                                 elsif ($pkg->{'builder'} eq $user) {
665                                         print "$name: Note: already taken by you.\n";
666                                         print "$name: ok\n" if $verbose;
667                                         return;
668                                 }
669                                 else {
670                                         $ok = 0;
671                                         $reason = "already taken by $pkg->{'builder'}";
672                                         $reason .= " (in newer version $pkg->{'version'})"
673                                                 if !version_eq($pkg->{'version'}, $version);
674                                 }
675                         }
676                 }
677                 elsif ($pkg->{'state'} =~ /^Failed/ &&
678                            pkg_version_eq($pkg, $version)) {
679                         if ($opt_override) {
680                                 print "The following package previously failed ",
681                                           "(by $pkg->{'builder'})\n",
682                                           "but overriding this as you request:\n";
683                                 send_mail( $pkg->{'builder'}, "failed package takeover",
684                                                    "The package '$name' (version $version) that ".
685                                                    "is taken by you\n".
686                                                    "and has failed previously has been taken over ".
687                                                    "by $user\n" )
688                                         if $pkg->{'builder'} ne $user;
689                         }
690                         else {
691                                 $ok = 0;
692                                 $reason = "build of $version failed previously:\n    ";
693                                 $reason .= join( "\n    ", split( "\n", $pkg->{'failed'} ));
694                                 $reason .= "\nalso the package doesn't need builing"
695                                         if $pkg->{'state'} eq 'Failed-Removed';
696                         }
697                 }
698         }
699         if ($ok) {
700             if ($api < 1) {
701                 my $ok = 'ok';
702                 if ($pkg->{'binary_nmu_version'}) {
703                         print "$name: Warning: needs binary NMU $pkg->{'binary_nmu_version'}\n" .
704                               "$pkg->{'binary_nmu_changelog'}\n";
705                         $ok = 'aok';
706                 } else {
707                         print "$name: Warning: Previous version failed!\n"
708                                 if $pkg->{'previous_state'} =~ /^Failed/ ||
709                                    $pkg->{'state'} =~ /^Failed/;
710                 }
711                 print "$name: $ok\n" if $verbose;
712             } else {
713                 print  "- $name:\n";
714                 print  "    - status: ok\n";
715                 printf "    - pkg-ver: %s_%s\n", $name, $version;
716                 print  "    - binNMU: $pkg->{'binary_nmu_version'}\n" if $pkg->{'binary_nmu_version'};
717                 print  "    - extra-changelog: $pkg->{'binary_nmu_changelog'}\n" if $pkg->{'binary_nmu_changelog'} && $pkg->{'binary_nmu_version'};
718                 print  "    - extra-depends: $pkg->{'extra_depends'}\n" if $pkg->{'extra_depends'};
719                 print  "    - extra-conflicts: $pkg->{'extra_conflicts'}\n" if $pkg->{'extra_conflicts'};
720                 print  "    - archive: $distributions{$distribution}->{'archive'}\n" if $distributions{$distribution}->{'archive'};
721                 print  "    - build_dep_resolver: $distributions{$distribution}->{'build_dep_resolver'}\n" if $distributions{$distribution}->{'build_dep_resolver'};
722                 print  "    - arch_all: $pkg->{'build_arch_all'}\n" if $pkg->{'build_arch_all'};
723                 print  "    - suppress_successful_logs: $distributions{$distribution}->{'suppress_successful_logs'}\n" if $distributions{$distribution}->{'suppress_successful_logs'};
724             }
725                 change_state( \$pkg, 'Building' );
726                 $pkg->{'package'} = $name;
727                 $pkg->{'version'} = $version;
728                 $pkg->{'builder'} = $user;
729                 log_ta( $pkg, "--take" );
730                 update_source_info($pkg);
731         }
732         else {
733             if ($api < 1) {
734                 print "$name: NOT OK!\n  $reason\n";
735             } else {
736                 print "- $name:\n    - status: not ok\n    - reason: \"$reason\"\n";
737             }
738         }
739 }
740
741 sub add_one_attempted {
742         my $name = shift;
743         my $version = shift;
744         my $pkg = get_source_info($name);
745
746         if (!defined($pkg)) {
747                 print "$name: not registered yet.\n";
748                 return;
749         }
750
751         if (($pkg->{'state'} ne "Building") && ($pkg->{'state'} ne "Build-Attempted")) {
752                 print "$name: not taken for building (state is $pkg->{'state'}). ",
753                           "Skipping.\n";
754                 return;
755         }
756         if ($pkg->{'builder'} ne $user) {
757                 print "$name: not taken by you, but by $pkg->{'builder'}. Skipping.\n";
758                 return;
759         }
760         elsif ( !pkg_version_eq($pkg, $version) ) {
761                 print "$name: version mismatch ".
762                           "$(pkg->{'version'} ".
763                           "by $pkg->{'builder'})\n";
764                 return;
765         }
766
767         change_state( \$pkg, 'Build-Attempted' );
768         log_ta( $pkg, "--attempted" );
769         update_source_info($pkg);
770         print "$name: registered as uploaded\n" if $verbose;
771 }
772
773 sub add_one_built {
774         my $name = shift;
775         my $version = shift;
776         my $pkg = get_source_info($name);
777
778         if (!defined($pkg)) {
779                 print "$name: not registered yet.\n";
780                 return;
781         }
782
783         if (($pkg->{'state'} ne "Building") && ($pkg->{'state'} ne "Build-Attempted")) {
784                 print "$name: not taken for building (state is $pkg->{'state'}). ",
785                           "Skipping.\n";
786                 return;
787         }
788         if ($pkg->{'builder'} ne $user) {
789                 print "$name: not taken by you, but by $pkg->{'builder'}. Skipping.\n";
790                 return;
791         }
792         elsif ( !pkg_version_eq($pkg, $version) ) {
793                 print "$name: version mismatch ".
794                           "$(pkg->{'version'} ".
795                           "by $pkg->{'builder'})\n";
796                 return;
797         }
798         change_state( \$pkg, 'Built' );
799         log_ta( $pkg, "--built" );
800         update_source_info($pkg);
801         print "$name: registered as built\n" if $verbose;
802 }
803
804 sub add_one_uploaded {
805         my $name = shift;
806         my $version = shift;
807         my $pkg = get_source_info($name);
808
809         if (!defined($pkg)) {
810                 print "$name: not registered yet.\n";
811                 return;
812         }
813
814         if ($pkg->{'state'} eq "Uploaded" &&
815                 pkg_version_eq($pkg,$version)) {
816                 print "$name: already uploaded\n";
817                 return;
818         }
819         if (!isin( $pkg->{'state'}, qw(Building Built Build-Attempted))) {
820                 print "$name: not taken for building (state is $pkg->{'state'}). ",
821                           "Skipping.\n";
822                 return;
823         }
824         if ($pkg->{'builder'} ne $user) {
825                 print "$name: not taken by you, but by $pkg->{'builder'}. Skipping.\n";
826                 return;
827         }
828         # strip epoch -- buildd-uploader used to go based on the filename.
829         # (to remove at some point)
830         my $pkgver;
831         ($pkgver = $pkg->{'version'}) =~ s/^\d+://;
832         $version =~ s/^\d+://; # for command line use
833         if ($pkg->{'binary_nmu_version'} ) {
834                 my $nmuver = binNMU_version($pkgver, $pkg->{'binary_nmu_version'});
835                 if (!version_eq( $nmuver, $version )) {
836                         print "$name: version mismatch ($nmuver registered). ",
837                                   "Skipping.\n";
838                         return;
839                 }
840         } elsif (!version_eq($pkgver, $version)) {
841                 print "$name: version mismatch ($pkg->{'version'} registered). ",
842                           "Skipping.\n";
843                 return;
844         }
845
846         change_state( \$pkg, 'Uploaded' );
847         log_ta( $pkg, "--uploaded" );
848         update_source_info($pkg);
849         print "$name: registered as uploaded\n" if $verbose;
850 }
851
852 sub add_one_failed {
853         my $name = shift;
854         my $version = shift;
855         my ($state, $cat);
856         my $pkg = get_source_info($name);
857
858         if (!defined($pkg)) {
859                 print "$name: not registered yet.\n";
860                 return;
861         }
862         $state = $pkg->{'state'};
863
864         if ($state eq "Not-For-Us") {
865                 print "$name: not suitable for this architecture anyway. Skipping.\n";
866                 return;
867         }
868         elsif ($state eq "Failed-Removed") {
869                 print "$name: failed previously and doesn't need building. Skipping.\n";
870                 return;
871         }
872         elsif ($state eq "Installed") {
873                 print "$name: Is already installed in archive. Skipping.\n";
874                 return;
875         }
876         elsif ($pkg->{'builder'} &&
877                    (($user ne $pkg->{'builder'}) &&
878                     !($pkg->{'builder'} =~ /^(\w+)-\w+/ && $1 eq $user))) {
879                 print "$name: not taken by you, but by ".
880                           "$pkg->{'builder'}. Skipping.\n";
881                 return;
882         }
883         elsif ( !pkg_version_eq($pkg, $version) ) {
884                 print "$name: version mismatch ".
885                           "$(pkg->{'version'} ".
886                           "by $pkg->{'builder'})\n";
887                 return;
888         }
889
890         $cat = $category;
891         if (!$cat && $fail_reason =~ /^\[([^\]]+)\]/) {
892                 $cat = $1;
893                 $cat = $short_category{$cat} if exists $short_category{$cat};
894                 if (!isin( $cat, values %short_category )) {
895                         print "$name: Warning: unknown category $cat; discarded\n";
896                         $cat = "";
897                 }
898                 $fail_reason =~ s/^\[[^\]]+\][ \t]*\n*//;
899         }
900
901         if ($state eq "Needs-Build") {
902                 print "$name: Warning: not registered for building previously, ".
903                           "but processing anyway.\n";
904         }
905         elsif ($state eq "Uploaded") {
906                 print "$name: Warning: marked as uploaded previously, ".
907                           "but processing anyway.\n";
908         }
909         elsif ($state eq "Dep-Wait") {
910                 print "$name: Warning: marked as waiting for dependencies, ".
911                           "but processing anyway.\n";
912         }
913         elsif ($state eq "BD-Uninstallable") {
914                 print "$name: Warning: marked as having uninstallable build-dependencies, ".
915                           "but processing anyway.\n";
916         }
917         elsif ($state eq "Failed") {
918                 print "$name: already registered as failed; will append new message\n"
919                         if $fail_reason;
920                 print "$name: already registered as failed; changing category\n"
921                         if $cat;
922         }
923
924         if (($cat eq "reminder-sent" || $cat eq "nmu-offered") &&
925                 defined $pkg->{'failed_category'} &&
926                 $pkg->{'failed_category'} ne $cat) {
927                 (my $action = $cat) =~ s/-/ /;
928                 $fail_reason .= "\n$short_date: $action";
929         }
930
931         change_state( \$pkg, 'Failed' );
932         $pkg->{'builder'} = $user;
933         $pkg->{'failed'} .= "\n" if $pkg->{'failed'};
934         $pkg->{'failed'} .= $fail_reason;
935         $pkg->{'failed_category'} = $cat if $cat;
936         if (defined $pkg->{'permbuildpri'}) {
937                 $pkg->{'buildpri'} = $pkg->{'permbuildpri'};
938         } else {
939                 delete $pkg->{'buildpri'};
940         }
941         log_ta( $pkg, "--failed" );
942         update_source_info($pkg);
943         print "$name: registered as failed\n" if $verbose;
944 }
945
946 sub add_one_notforus {
947         my $name = shift;
948         my $version = shift;
949         my $pkg = get_source_info($name);
950
951         if ($pkg->{'state'} eq 'Not-For-Us') {
952                 # reset Not-For-Us state in case it's called twice; this is
953                 # the only way to get a package out of this state...
954                 # There is no really good state in which such packages should
955                 # be put :-( So use Failed for now.
956                 change_state( \$pkg, 'Failed' );
957                 $pkg->{'package'} = $name;
958                 $pkg->{'failed'} = "Was Not-For-Us previously";
959                 delete $pkg->{'builder'};
960                 delete $pkg->{'depends'};
961                 log_ta( $pkg, "--no-build(rev)" );
962                 print "$name: now not unsuitable anymore\n";
963
964                 send_mail( $conf::notforus_maint,
965                                    "$name moved out of Not-For-Us state",
966                                    "The package '$name' has been moved out of the Not-For-Us ".
967                                    "state by $user.\n".
968                                    "It should probably also be removed from ".
969                                    "Packages-arch-specific or\n".
970                                    "the action was wrong.\n" )
971                         if $conf::notforus_maint;
972         }
973         else {
974                 change_state( \$pkg, 'Not-For-Us' );
975                 $pkg->{'package'} = $name;
976                 delete $pkg->{'builder'};
977                 delete $pkg->{'depends'};
978                 delete $pkg->{'buildpri'};
979                 delete $pkg->{'binary_nmu_version'};
980                 delete $pkg->{'binary_nmu_changelog'};
981                 log_ta( $pkg, "--no-build" );
982                 print "$name: registered as unsuitable\n" if $verbose;
983
984                 send_mail( $conf::notforus_maint,
985                                    "$name set to Not-For-Us",
986                                    "The package '$name' has been set to state Not-For-Us ".
987                                    "by $user.\n".
988                                    "It should probably also be added to ".
989                                    "Packages-arch-specific or\n".
990                                    "the Not-For-Us state is wrong.\n" )
991                         if $conf::notforus_maint;
992         }
993         update_source_info($pkg);
994 }
995
996 sub add_one_needsbuild {
997         my $name = shift;
998         my $version = shift;
999         my $state;
1000         my $pkg = get_source_info($name);
1001
1002         if (!defined($pkg)) {
1003                 print "$name: not registered; can't give back.\n";
1004                 return;
1005         }
1006         $state = $pkg->{'state'};
1007
1008         if ($state eq "BD-Uninstallable") {
1009                 if ($opt_override) {
1010                         print "$name: Forcing uninstallability mark to be removed. This is not permanent and might be reset with the next trigger run\n";
1011
1012                         change_state( \$pkg, 'Needs-Build' );
1013                         delete $pkg->{'builder'};
1014                         delete $pkg->{'depends'};
1015                         log_ta( $pkg, "--give-back" );
1016                         update_source_info($pkg);
1017                         print "$name: given back\n" if $verbose;
1018                         return;
1019                 }
1020                 else {
1021                         print "$name: has uninstallable build-dependencies. Skipping\n",
1022                                   "  (use --override to clear dependency list and ",
1023                                   "give back anyway)\n";
1024                         return;
1025                 }
1026         }
1027         elsif ($state eq "Dep-Wait") {
1028                 if ($opt_override) {
1029                         print "$name: Forcing source dependency list to be cleared\n";
1030                 }
1031                 else {
1032                         print "$name: waiting for source dependencies. Skipping\n",
1033                                   "  (use --override to clear dependency list and ",
1034                                   "give back anyway)\n";
1035                         return;
1036                 }
1037         }
1038         elsif (!isin( $state, qw(Building Built Build-Attempted))) {
1039                 print "$name: not taken for building (state is $state).";
1040                 if ($opt_override) {
1041                         print "\n$name: Forcing give-back\n";
1042                 }
1043                 else {
1044                         print " Skipping.\n";
1045                         return;
1046                 }
1047         }
1048         if (defined ($pkg->{'builder'}) && $user ne $pkg->{'builder'} &&
1049                 !($pkg->{'builder'} =~ /^(\w+)-\w+/ && $1 eq $user) &&
1050                 !$opt_override) {
1051                 print "$name: not taken by you, but by ".
1052                           "$pkg->{'builder'}. Skipping.\n";
1053                 return;
1054         }
1055         if (!pkg_version_eq($pkg, $version)) {
1056                 print "$name: version mismatch ($pkg->{'version'} registered). ",
1057                           "Skipping.\n";
1058                 return;
1059         }
1060         if (!defined $distributions{$distribution}{noadw}) {
1061                 change_state( \$pkg, 'BD-Uninstallable' );
1062                 $pkg->{'bd_problem'} = "Installability of build dependencies not tested yet";
1063         } else {
1064                 change_state( \$pkg, 'Needs-Build' );
1065         }
1066         $pkg->{'builder'} = undef;
1067         $pkg->{'depends'} = undef;
1068         log_ta( $pkg, "--give-back" );
1069         update_source_info($pkg);
1070         print "$name: given back\n" if $verbose;
1071 }
1072
1073 sub set_one_binnmu {
1074         my $name = shift;
1075         my $version = shift;
1076         my $pkg = get_source_info($name);
1077         my $state;
1078
1079         if (!defined($pkg)) {
1080                 print "$name: not registered; can't register for binNMU.\n";
1081                 return;
1082         }
1083         my $db_ver = $pkg->{'version'};
1084
1085         if (!version_eq($db_ver, $version)) {
1086                 print "$name: version mismatch ($db_ver registered). ",
1087                           "Skipping.\n";
1088                 return;
1089         }
1090         $state = $pkg->{'state'};
1091
1092         if (defined $pkg->{'binary_nmu_version'}) {
1093                 if ($binNMUver == 0) {
1094                         change_state( \$pkg, 'Installed' );
1095                         delete $pkg->{'builder'};
1096                         delete $pkg->{'depends'};
1097                         delete $pkg->{'binary_nmu_version'};
1098                         delete $pkg->{'binary_nmu_changelog'};
1099                 } elsif ($binNMUver <= $pkg->{'binary_nmu_version'}) {
1100                         print "$name: already building binNMU $pkg->{'binary_nmu_version'}\n";
1101                         return;
1102                 } else {
1103                         $pkg->{'binary_nmu_version'} = $binNMUver;
1104                         $pkg->{'binary_nmu_changelog'} = $fail_reason;
1105                         $pkg->{'notes'} = 'out-of-date';
1106                         $pkg->{'buildpri'} = $pkg->{'permbuildpri'}
1107                                 if (defined $pkg->{'permbuildpri'});
1108                         if (defined $distributions{$distribution}{noadw}) {
1109                                 change_state( \$pkg, 'Installed' );
1110                         } else {
1111                                 change_state( \$pkg, 'BD-Uninstallable' );
1112                         }
1113                 }
1114                 log_ta( $pkg, "--binNMU" );
1115                 update_source_info($pkg);
1116                 return;
1117         } elsif ($binNMUver == 0) {
1118                 print "${name}_$version: no scheduled binNMU to cancel.\n";
1119                 return;
1120         }
1121
1122         if ($state ne 'Installed') {
1123                 print "${name}_$version: not installed; can't register for binNMU.\n";
1124                 return;
1125         }
1126
1127         my $fullver = binNMU_version($version,$binNMUver);
1128         if ( version_lesseq( $fullver, $pkg->{'installed_version'} ) )
1129         {
1130                 print "$name: binNMU $fullver is not newer than current version $pkg->{'installed_version'}\n";
1131                 return;
1132         }
1133
1134         if (!defined $distributions{$distribution}{noadw}) {
1135                 change_state( \$pkg, 'BD-Uninstallable' );
1136                 $pkg->{'bd_problem'} = "Installability of build dependencies not tested yet";
1137         }
1138         else
1139         {
1140                 change_state( \$pkg, 'Needs-Build' );
1141         }
1142         delete $pkg->{'builder'};
1143         delete $pkg->{'depends'};
1144         $pkg->{'binary_nmu_version'} = $binNMUver;
1145         $pkg->{'binary_nmu_changelog'} = $fail_reason;
1146         $pkg->{'notes'} = 'out-of-date';
1147         log_ta( $pkg, "--binNMU" );
1148         update_source_info($pkg);
1149         print "${name}: registered for binNMU $fullver\n" if $verbose;
1150 }
1151
1152 sub set_one_buildpri {
1153         my $name = shift;
1154         my $version = shift;
1155         my $key = shift;
1156         my $pkg = get_source_info($name);
1157         my $state;
1158
1159         if (!defined($pkg)) {
1160                 print "$name: not registered; can't set priority.\n";
1161                 return;
1162         }
1163         $state = $pkg->{'state'};
1164
1165         if ($state eq "Not-For-Us") {
1166                 print "$name: not suitable for this architecture. Skipping.\n";
1167                 return;
1168         } elsif ($state eq "Failed-Removed") {
1169                 print "$name: failed previously and doesn't need building. Skipping.\n";
1170                 return;
1171         }
1172         if (!pkg_version_eq($pkg, $version)) {
1173                 print "$name: version mismatch ($pkg->{'version'} registered). ",
1174                           "Skipping.\n";
1175                 return;
1176         }
1177         if ( $build_priority == 0 ) {
1178                 delete $pkg->{'buildpri'}
1179                         if $key eq 'permbuildpri' and defined $pkg->{'buildpri'}
1180                         and $pkg->{'buildpri'} == $pkg->{$key};
1181                 delete $pkg->{$key};
1182         } else {
1183                 $pkg->{'buildpri'} = $build_priority
1184                         if $key eq 'permbuildpri';
1185                 $pkg->{$key} = $build_priority;
1186         }
1187         update_source_info($pkg);
1188         print "$name: set to build priority $build_priority\n" if $verbose;
1189 }
1190
1191 sub add_one_depwait {
1192         my $name = shift;
1193         my $version = shift;
1194         my $state;
1195         my $pkg = get_source_info($name);
1196
1197         if (!defined($pkg)) {
1198                 print "$name: not registered yet.\n";
1199                 return;
1200         }
1201         $state = $pkg->{'state'};
1202
1203         if ($state eq "Dep-Wait") {
1204                 print "$name: merging with previously registered dependencies\n";
1205         }
1206         
1207         if (isin( $state, qw(Needs-Build Failed BD-Uninstallable))) {
1208                 print "$name: Warning: not registered for building previously, ".
1209                           "but processing anyway.\n";
1210         }
1211         elsif ($state eq "Not-For-Us") {
1212                 print "$name: not suitable for this architecture anyway. Skipping.\n";
1213                 return;
1214         }
1215         elsif ($state eq "Failed-Removed") {
1216                 print "$name: failed previously and doesn't need building. Skipping.\n";
1217                 return;
1218         }
1219         elsif ($state eq "Installed") {
1220                 print "$name: Is already installed in archive. Skipping.\n";
1221                 return;
1222         }
1223         elsif ($state eq "Uploaded") {
1224                 print "$name: Is already uploaded. Skipping.\n";
1225                 return;
1226         }
1227         elsif ($pkg->{'builder'} &&
1228                    $user ne $pkg->{'builder'}) {
1229                 print "$name: not taken by you, but by ".
1230                           "$pkg->{'builder'}. Skipping.\n";
1231                 return;
1232         }
1233         elsif ( !pkg_version_eq($pkg,$version)) {
1234                 print "$name: version mismatch ".
1235                           "($pkg->{'version'} ".
1236                           "by $pkg->{'builder'})\n";
1237                 return;
1238         }
1239         elsif ($fail_reason =~ /^\s*$/ ||
1240                    !parse_deplist( $fail_reason, 1 )) {
1241                 print "$name: Bad dependency list\n";
1242                 return;
1243         }
1244         change_state( \$pkg, 'Dep-Wait' );
1245         $pkg->{'builder'} = $user;
1246         if (defined $pkg->{'permbuildpri'}) {
1247                 $pkg->{'buildpri'} = $pkg->{'permbuildpri'};
1248         } else {
1249                 delete $pkg->{'buildpri'};
1250         }
1251         my $deplist = parse_deplist( $pkg->{'depends'} );
1252         my $new_deplist = parse_deplist( $fail_reason );
1253         # add new dependencies, maybe overwriting old entries
1254         foreach (keys %$new_deplist) {
1255                 $deplist->{$_} = $new_deplist->{$_};
1256         }
1257         $pkg->{'depends'} = build_deplist($deplist);
1258         log_ta( $pkg, "--dep-wait" );
1259         update_source_info($pkg);
1260         print "$name: registered as waiting for dependencies\n" if $verbose;
1261 }
1262
1263 sub set_one_update {
1264         my $name = shift;
1265         my $version = shift;
1266         my $pkg = get_source_info($name);
1267
1268         if (!defined($pkg)) {
1269                 print "$name: not registered yet.\n";
1270                 return;
1271         }
1272         $pkg->{'version'} =~ s/\+b[0-9]+$//;
1273
1274         log_ta( $pkg, "--update" );
1275         update_source_info($pkg);
1276 }
1277
1278
1279 # for sorting priorities and sections
1280 BEGIN {
1281         %prioval = ( required             => -5,
1282                                  important            => -4,
1283                                  standard             => -3,
1284                                  optional             => -2,
1285                                  extra                => -1,
1286                                  unknown              => -1 );
1287         %sectval = ( 
1288                                  libs                   => -200,
1289                                  'debian-installer'     => -199,
1290                                  base                   => -198,
1291                                  devel                  => -197,
1292                                  kernel                 => -196,
1293                                  shells                 => -195,
1294                                  perl                   => -194,
1295                                  python                 => -193,
1296                                  graphics               => -192,
1297                                  admin                  => -191,
1298                                  utils                  => -190,
1299                                  x11                    => -189,
1300                                  editors                => -188,
1301                                  net                    => -187,
1302                                  httpd                  => -186,
1303                                  mail                   => -185,
1304                                  news                   => -184,
1305                                  tex                    => -183,
1306                                  text                   => -182,
1307                                  web                    => -181,
1308                                  vcs                    => -180,
1309                                  doc                    => -179,
1310                                  localizations          => -178,
1311                                  interpreters           => -177,
1312                                  ruby                   => -176,
1313                                  java                   => -175,
1314                                  ocaml                  => -174,
1315                                  lisp                   => -173,
1316                                  haskell                => -172,
1317                                  'cli-mono'             => -171,
1318                                  gnome                  => -170,
1319                                  kde                    => -169,
1320                                  xfce                   => -168,
1321                                  gnustep                => -167,
1322                                  database               => -166,
1323                                  video                  => -165,
1324                                  debug                  => -164,
1325                                  games                  => -163,
1326                                  misc                   => -162,
1327                                  fonts                  => -161,
1328                                  otherosfs              => -160,
1329                                  oldlibs                => -159,
1330                                  libdevel               => -158,
1331                                  sound                  => -157,
1332                                  math                   => -156,
1333                                  'gnu-r'                => -155,
1334                                  science                => -154,
1335                                  comm                   => -153,
1336                                  electronics            => -152,
1337                                  hamradio               => -151,
1338                                  embedded               => -150,
1339                                  php                    => -149,
1340                                  zope                   => -148,
1341         );
1342         foreach my $i (keys %sectval) {
1343                 $sectval{"contrib/$i"} = $sectval{$i}+40;
1344                 $sectval{"non-free/$i"} = $sectval{$i}+80;
1345         }
1346         $sectval{'unknown'}     = -165;
1347
1348         %catval =  ( "none"                           => -20,
1349                                  "uploaded-fixed-pkg" => -19,
1350                                  "fix-expected"       => -18,
1351                                  "reminder-sent"      => -17,
1352                                  "nmu-offered"        => -16,
1353                                  "easy"               => -15,
1354                                  "medium"                     => -14,
1355                                  "hard"                   => -13,
1356                                  "compiler-error"     => -12 );
1357 }
1358
1359 sub sort_list_func {
1360     my $map_funcs = {
1361         'C' => ['<->', sub { return $_[0]->{'calprio'}; }],
1362         'W' => ['<->', sub { return $_[0]->{'state_days'}; }],
1363         'P' => ['<->', sub { return $_[0]->{'buildpri'}; }],
1364         'p' => ['<=>', sub { return $prioval{$_[0]->{'priority'}//""}//0; }],
1365         's' => ['<=>', sub { return $sectval{$_[0]->{'section'}//""}//0; }],
1366         'n' => ['cmp', sub { return $_[0]->{'package'}; }],
1367         'b' => ['cmp', sub { return $_[0]->{'builder'}; }],
1368         'c' => ['<=>', sub { return ($_[0]->{'notes'}//"" =~ /^(out-of-date|partial)/) ? 0: ($_[0]->{'notes'}//"" =~ /^uncompiled/) ? 2 : 1; }],
1369         'f' => ['<=>', sub { return $catval{ $_[0]->{'failed_category'} ? $_[0]->{'failed_category'}: "none" }; }],
1370         'S' => ['<->', sub { return isin($_[0]->{'priority'}, qw(required important standard)); }],
1371         'T' => ['<->', sub { return $_[0]->{'state_time'} % 86400;} ], # Fractions of a day
1372     };
1373
1374         foreach my $letter (split( //, $list_order )) {
1375             my $r;
1376             $r = (&{$map_funcs->{$letter}[1]}($b)//0 ) <=> (&{$map_funcs->{$letter}[1]}($a)//0 ) if $map_funcs->{$letter}[0] eq '<->';
1377             $r = (&{$map_funcs->{$letter}[1]}($a)//0 ) <=> (&{$map_funcs->{$letter}[1]}($b)//0 ) if $map_funcs->{$letter}[0] eq '<=>';
1378             $r = (&{$map_funcs->{$letter}[1]}($a)//"") cmp (&{$map_funcs->{$letter}[1]}($b)//"") if $map_funcs->{$letter}[0] eq 'cmp';
1379             return $r if $r != 0;
1380         }
1381         return 0;
1382 }
1383
1384 sub calculate_prio {
1385         my $priomap = $yamlmap->{priority};
1386         my $pkg = shift;
1387         my @s=split("/", $pkg->{'section'});
1388         $pkg->{'component'} = $s[0] if $s[1];
1389         $pkg->{'component'} ||= 'main';
1390         $pkg->{'calprio'} = 0;
1391         foreach my $k (keys %{$priomap->{keys}}) {
1392                 $pkg->{'calprio'} += $priomap->{keys}->{$k}{$pkg->{$k}} if $pkg->{$k} and $priomap->{keys}->{$k}{$pkg->{$k}};
1393         }
1394
1395         my $days = $pkg->{'state_days'};
1396         $days = $priomap->{'waitingdays'}->{'min'} if $priomap->{'waitingdays'}->{'min'} and $days < $priomap->{'waitingdays'}->{'min'};
1397         $days = $priomap->{'waitingdays'}->{'max'} if $priomap->{'waitingdays'}->{'max'} and $days > $priomap->{'waitingdays'}->{'max'};
1398         my $scale = $priomap->{'waitingdays'}->{'scale'} || 1;
1399         $pkg->{'calprio'} += $days * $scale;
1400
1401         my $btime = max($pkg->{'anytime'}//0, $pkg->{'successtime'}//0);
1402         my $bhours = $btime ? int($btime/3600) : ($priomap->{'buildhours'}->{'default'} || 2);
1403         $bhours = $priomap->{'buildhours'}->{'min'} if $priomap->{'buildhours'}->{'min'} and $bhours < $priomap->{'buildhours'}->{'min'};
1404         $bhours = $priomap->{'buildhours'}->{'max'} if $priomap->{'buildhours'}->{'max'} and $bhours > $priomap->{'buildhours'}->{'max'};
1405         $scale = $priomap->{'buildhours'}->{'scale'} || 1;
1406         $pkg->{'calprio'} -= $bhours * $scale;
1407
1408         $pkg->{'calprio'} += $pkg->{'permbuildpri'} if  $pkg->{'permbuildpri'};
1409         $pkg->{'calprio'} += $pkg->{'buildpri'} if  $pkg->{'buildpri'};
1410
1411         return $pkg;
1412 }
1413
1414
1415 sub seconds2time {
1416     my $t = shift;
1417     return "" unless $t;
1418     my $sec = $t % 60;
1419     my $min = int($t/60) % 60;
1420     my $hours = int($t / 3600);
1421     return sprintf("%d:%02d:%02d", $hours, $min, $sec) if $hours;
1422     return sprintf("%d:%02d", $min, $sec);
1423 }
1424
1425
1426 sub use_fmt {
1427     my $r;
1428
1429     if (ref($_[0]) eq 'CODE') {
1430         $r = &{$_[0]};
1431     } else {
1432         $r = $_[0];
1433     }
1434
1435     shift;
1436     my $t = shift;
1437
1438     $r ||= "";
1439     return $r unless $t;
1440
1441     my $pkg = shift;
1442     my $var = shift;
1443     if (substr($t,0,1) eq '!') {
1444         $t = substr($t,1);
1445         return "" if $r;
1446     } else {
1447         return "" unless $r;
1448     }
1449     if ($t =~ /%/) {
1450         return print_format($t, $pkg, $var);
1451     }
1452     return $t;
1453 }
1454 sub make_fmt { my $c = shift; my $pkg = shift; my $var = shift; return sub { use_fmt($c, $_[0], $pkg, $var); } };
1455
1456 sub print_format {
1457     my $printfmt = shift;
1458     my $pkg = shift;
1459     my $var = shift;
1460
1461 =pod
1462
1463 Within an format string, the following values are allowed (need to be preceded by %).
1464 This can be combined to e.g.
1465 wanna-build --format='wanna-build -A %a --give-back %p_%v' -A mipsel --list=failed
1466
1467 a Architecture
1468 c section (e.g. libs or utils)
1469 D in case of BD-Uninstallable the reason for the uninstallability
1470 d distribution
1471 E in case of Dep-Wait the packages being waited on, in case of Needs-Build the number in the queue
1472 F in case of Failed the fail reason
1473 n newline
1474 o time of last successful build (seconds)
1475 O time of last successful build (formated)
1476 P previous state
1477 p Package name
1478 q time of last build (seconds)
1479 Q time of last build (formated)
1480 r max time of last (successful) build (seconds)
1481 R max time of last (successful) build (formated)
1482 S Package state
1483 s Time in this state in full seconds since epoch
1484 t time of state change
1485 T time since state change
1486 u Builder (e.g. buildd_mipsel-rem)
1487 v Package version
1488 V full Package version (i.e. with +b.., = %v%{+b}B%B
1489 X the string normally between [], e.g. optional:out-of-date:calprio{61}:days{25}
1490
1491 %{Text}?  print Text in case ? is not empty; ? is never printed
1492 %{!Text}? print Text in case ? is empty; ? is never printed
1493 Text could contain further %. To start with !, use %!
1494
1495 =cut
1496
1497     return stringf($printfmt, (
1498         'p' => make_fmt( $pkg->{'package'}, $pkg, $var),
1499         'a' => make_fmt( $arch, $pkg, $var),
1500         's' => make_fmt( sub { return floor(str2time($pkg->{'state_change'})); }, $pkg, $var),
1501         'v' => make_fmt( $pkg->{'version'}, $pkg, $var),
1502         'V' => make_fmt( sub { $pkg->{'binary_nmu_version'} ? $pkg->{'version'}."+b".$pkg->{'binary_nmu_version'} : $pkg->{'version'} }, $pkg, $var),
1503         'S' => make_fmt( $pkg->{'state'}, $pkg, $var),
1504         'u' => make_fmt( $pkg->{'builder'}, $pkg, $var),
1505         'X' => make_fmt( sub {
1506             no warnings;
1507             my $c = "$pkg->{'priority'}:$pkg->{'notes'}";
1508             $c .= ":PREV-FAILED" if $pkg->{'previous_state'} && $pkg->{'previous_state'} =~ /^Failed/;
1509             $c .= ":bp{" . $pkg->{'buildpri'} . "}" if defined $pkg->{'buildpri'};
1510             $c .= ":binNMU{" . $pkg->{'binary_nmu_version'} . "}" if defined $pkg->{'binary_nmu_version'};
1511             $c .= ":calprio{". $pkg->{'calprio'}."}";
1512             $c .= ":days{". $pkg->{'state_days'}."}";
1513             return $c;
1514             }, $pkg, $var),
1515         'c' => make_fmt( $pkg->{'section'}, $pkg, $var),
1516         'P' => make_fmt( $pkg->{'previous_state'} || "unknwon", $pkg, $var),
1517         'E' => make_fmt( sub { return $pkg->{'depends'} if $pkg->{'state'} eq "Dep-Wait";
1518             return $var->{scnt}{'Needs-Build'} + 1 if $pkg->{'state'} eq 'Needs-Build';
1519             return ""; }, $pkg, $var),
1520         'F' => make_fmt( sub { return "" unless $pkg->{'failed'};
1521             my $failed = $pkg->{'failed'};
1522             $failed =~ s/\\/\\\\/g;
1523             return $pkg->{'package'}."#".$arch."-failure\n ".
1524             join("\\0a",split("\n",$failed))."\\0a\n"; }, $pkg, $var),
1525         'D' => make_fmt( sub { return "" unless $pkg->{'bd_problem'};
1526             return $pkg->{'package'}."#".$arch."-bd-problem\n".
1527             join("\\0a",split("\n",$pkg->{'bd_problem'}))."\\0a\n"; }, $pkg, $var),
1528         'B' => make_fmt( sub { return $pkg->{'binary_nmu_version'} if defined $pkg->{'binary_nmu_version'}; }, $pkg, $var),
1529         'd' => make_fmt( $pkg->{'distribution'}, $pkg, $var),
1530         't' => make_fmt( $pkg->{'state_change'}, $pkg, $var),
1531         'T' => make_fmt( sub { return seconds2time(time() - floor(str2time($pkg->{'state_change'}))); }, $pkg, $var),
1532         'o' => make_fmt( $pkg->{'successtime'}, $pkg, $var),
1533         'O' => make_fmt( sub { return seconds2time ( $pkg->{'successtime'}); }, $pkg, $var),
1534         'q' => make_fmt( $pkg->{'anytime'}, $pkg, $var),
1535         'Q' => make_fmt( sub { return seconds2time ( $pkg->{'anytime'}); }, $pkg, $var),
1536         'r' => make_fmt( sub { my $c = max($pkg->{'successtime'}//0, $pkg->{'anytime'}//0); return $c if $c; return; }, $pkg, $var),
1537         'R' => make_fmt( sub { return seconds2time ( max($pkg->{'successtime'}//0, $pkg->{'anytime'}//0)); }, $pkg, $var),
1538     ));
1539 }
1540
1541 sub list_packages {
1542         my $state = shift;
1543         my( $name, $pkg, @list );
1544         my $cnt = 0;
1545         my %scnt;
1546         my $ctime = time;
1547
1548         my $db = get_all_source_info(state => $state, user => $user, category => $category, list_min_age => $list_min_age);
1549         foreach $name (keys %$db) {
1550                 next if $name =~ /^_/;
1551                 push @list, calculate_prio($db->{$name});
1552         }
1553
1554         # filter components
1555         @list = grep { my $i = $_->{'component'}; grep { $i eq $_ } split /[, ]+/, $yamlmap->{"restrict"}{'component'} } @list;
1556         # extra depends / conflicts only from api 1 on
1557         @list = grep { !$_->{'extra_depends'} and !$_->{'extra_conflicts'} } @list if $api < 1 ;
1558
1559         # first adjust ownprintformat, then set printformat accordingly
1560         $printformat ||= $yamlmap->{"format"}{$ownprintformat} if $ownprintformat;
1561         $printformat ||= $yamlmap->{"format"}{"default"}{$state};
1562         $printformat ||= $yamlmap->{"format"}{"default"}{"default"};
1563         undef $printformat if ($ownprintformat && $ownprintformat eq 'none');
1564
1565         foreach $pkg (sort sort_list_func @list) {
1566                 if ($printformat) {
1567                     print print_format($printformat, $pkg, {'cnt' => $cnt, 'scnt' => \%scnt})."\n";
1568                     ++$cnt;
1569                     $scnt{$pkg->{'state'}}++;
1570                     next;
1571                 }
1572                 print print_format("%c/%p_%v", $pkg, {});
1573                 print print_format(": %S", $pkg, {})
1574                         if $state eq "all";
1575                 print print_format("%{ by }u%u", $pkg, {})
1576                         if $pkg->{'state'} ne "Needs-Build";
1577                 print print_format(" [%X]\n", $pkg, {});
1578                 print "  Reasons for failing:\n",
1579                           "    [Category: ",
1580                           defined $pkg->{'failed_category'} ? $pkg->{'failed_category'} : "none",
1581                           "]\n    ",
1582                           join("\n    ",split("\n",$pkg->{'failed'})), "\n"
1583                         if $pkg->{'state'} =~ /^Failed/;
1584                 print "  Dependencies: $pkg->{'depends'}\n"
1585                         if $pkg->{'state'} eq "Dep-Wait";
1586                 print "  Reasons for BD-Uninstallable:\n    ",
1587                           join("\n    ",split("\n",$pkg->{'bd_problem'})), "\n"
1588                         if $pkg->{'state'} eq "BD-Uninstallable";
1589                 print "  Previous state was $pkg->{'previous_state'}\n"
1590                         if $verbose && $pkg->{'previous_state'};
1591                 print "  No previous state recorded\n"
1592                         if $verbose && !$pkg->{'previous_state'};
1593                 print "  State changed at $pkg->{'state_change'}\n"
1594                         if $verbose && $pkg->{'state_change'};
1595                 print "  Previous state $pkg->{'previous_state'} left $pkg->{'state_time'} ago\n"
1596                         if $verbose && $pkg->{'previous_state'};
1597                 print "  Previous failing reasons:\n    ",
1598                       join("\n    ",split("\n",$pkg->{'old_failed'})), "\n"
1599                         if $verbose && $pkg->{'old_failed'};
1600                 ++$cnt;
1601                 $scnt{$pkg->{'state'}}++ if $state eq "all";
1602         }
1603         if ($state eq "all" && !$printformat) {
1604                 foreach (sort keys %scnt) {
1605                         print "Total $scnt{$_} package(s) in state $_.\n";
1606                 }
1607         }
1608         print "Total $cnt package(s)\n" unless $printformat;
1609         
1610 }
1611
1612 sub info_packages {
1613         my( $name, $pkg, $key, $dist );
1614         my @firstkeys = qw(package version builder state section priority
1615                                            installed_version previous_state state_change);
1616         my @dists = $info_all_dists ? keys %distributions : ($distribution);
1617         my %beautykeys = ( 'package' => 'Package', 'version' => 'Version', 'builder' => 'Builder',
1618                 'state' => 'State', 'section' => 'Section', 'priority' => 'Priority',
1619                 'installed_version' => 'Installed-Version', 'previous_state' => 'Previous-State',
1620                 'state_change' => 'State-Change',
1621                 'bd_problem' => 'BD-Problem', 
1622                 'binary_nmu_changelog' => 'Binary-NMU-Changelog', 'binary_nmu_version' => 'Binary-NMU-Version',
1623                 'buildpri' => 'BuildPri', 'depends' => 'Depends', 'failed' => 'Failed',
1624                 'failed_category' => 'Failed-Category', 'notes' => 'Notes',
1625                 'distribution' => 'Distribution', 'old_failed' => 'Old-Failed',
1626                 'permbuildpri' => 'PermBuildPri', 'rel' => 'Rel',
1627                 'calprio' => 'CalculatedPri', 'state_days' => 'State-Days', 'state_time' => 'State-Time',
1628                 'successtime' => 'Success-build-time',
1629                 'anytime' => 'Build-time',
1630                 'extra_depends' => 'Extra-Dependencies',
1631                 'extra_conflicts' => 'Extra-Conflicts',
1632                 'build_arch_all' => 'Build-Arch-All',
1633                          );
1634         
1635         foreach $name (@_) {
1636                 $name =~ s/_.*$//; # strip version
1637                 foreach $dist (@dists) {
1638                         my $pname = "$name" . ($info_all_dists ? "($dist)" : "");
1639                         
1640                         $pkg = get_readonly_source_info($name);
1641                         if (!defined( $pkg )) {
1642                                 print "$pname: not registered\n";
1643                                 next;
1644                         }
1645                         $pkg = calculate_prio($pkg);
1646
1647                         print "$pname:\n";
1648                         foreach $key (@firstkeys) {
1649                                 next if !defined $pkg->{$key};
1650                                 my $val = $pkg->{$key};
1651                                 chomp( $val );
1652                                 $val = "\n$val" if isin( $key, qw(Failed Old-Failed));
1653                                 $val =~ s/\n/\n    /g;
1654                                 my $print_key = $key;
1655                                 $print_key = $beautykeys{$print_key} if $beautykeys{$print_key};
1656                                 printf "  %-20s: %s\n", $print_key, $val;
1657                         }
1658                         foreach $key (sort keys %$pkg) {
1659                                 next if isin( $key, @firstkeys );
1660                                 my $val = $pkg->{$key};
1661                                 next if !defined($val);
1662                                 chomp( $val );
1663                                 $val = "\n$val" if isin( $key, qw(Failed Old-Failed));
1664                                 $val =~ s/\n/\n    /g;
1665                                 my $print_key = $key;
1666                                 $print_key = $beautykeys{$print_key} if $beautykeys{$print_key};
1667                                 printf "  %-20s: %s\n", $print_key, $val;
1668                         }
1669                 }
1670         }
1671 }
1672
1673 sub forget_packages {
1674         my( $name, $pkg, $key, $data );
1675         
1676         foreach $name (@_) {
1677                 $name =~ s/_.*$//; # strip version
1678                 $pkg = get_source_info($name);
1679                 if (!defined( $pkg )) {
1680                         print "$name: not registered\n";
1681                         next;
1682                 }
1683
1684                 $data = "";
1685                 foreach $key (sort keys %$pkg) {
1686                         my $val = $pkg->{$key};
1687                         chomp( $val );
1688                         $val =~ s/\n/\n /g;
1689                         $data .= sprintf "  %-20s: %s\n", $key, $val;
1690                 }
1691                 send_mail( $conf::db_maint,
1692                                    "$name deleted from DB " . table_name() . " " . $distribution,
1693                                    "The package '$name' has been deleted from the database ".
1694                                    "by $user.\n\n".
1695                                    "Data registered about the deleted package:\n".
1696                                    "$data\n" ) if $conf::db_maint;
1697                 change_state( \$pkg, 'deleted' );
1698                 log_ta( $pkg, "--forget" );
1699                 del_source_info($name);
1700                 print "$name: deleted from database\n" if $verbose;
1701         }
1702 }
1703
1704 sub forget_users {
1705         $dbh->do("DELETE from " . user_table_name() . 
1706                 " WHERE distribution = ?", undef, $distribution) or die $dbh->errstr;
1707 }
1708
1709 sub read_db {
1710         my $file = shift;
1711
1712         print "Reading ASCII database from $file..." if $verbose >= 1;
1713         open( my $fh, '<', $file ) or
1714                 die "Can't open database $file: $!\n";
1715
1716         local($/) = ""; # read in paragraph mode
1717         while( <$fh> ) {
1718                 my( %thispkg, $name );
1719                 s/[\s\n]+$//;
1720                 s/\n[ \t]+/\376\377/g;  # fix continuation lines
1721                 s/\376\377\s*\376\377/\376\377/og;
1722   
1723                 while( /^(\S+):[ \t]*(.*)[ \t]*$/mg ) {
1724                         my ($key, $val) = ($1, $2);
1725                         $key =~ s/-/_/g;
1726                         $key =~ tr/A-Z/a-z/;
1727                         $val =~ s/\376\377/\n/g;
1728                         $thispkg{$key} = $val;
1729                 }
1730                 check_entry( \%thispkg );
1731                 # add to db
1732                 if (exists($thispkg{'package'})) {
1733                         update_source_info(\%thispkg);
1734                 }
1735                 elsif(exists($thispkg{'user'})) {
1736                         # user in import, username in database.
1737                         $dbh->do('INSERT INTO ' . user_table_name() .
1738                                         ' (username, distribution, last_seen)' .
1739                                         ' values (?, ?, ?)',
1740                                 undef, $thispkg{'user'}, $distribution,
1741                                 $thispkg{'last_seen'})
1742                                 or die $dbh->errstr;
1743                  }
1744         }
1745         close( $fh );
1746         print "done\n" if $verbose >= 1;
1747 }
1748
1749 sub check_entry {
1750         my $pkg = shift;
1751         my $field;
1752
1753         return if $op_mode eq "manual-edit"; # no checks then
1754         
1755         # check for required fields
1756         if (exists $pkg->{'user'}) {
1757                 return;
1758         }
1759         if (!exists $pkg->{'package'}) {
1760                 print STDERR "Bad entry: ",
1761                           join( "\n", map { "$_: $pkg->{$_}" } keys %$pkg ), "\n";
1762                 die "Database entry lacks package or username field\n";
1763         }
1764         # if no State: field, generate one (for old db compat)
1765         if (!exists($pkg->{'state'})) {
1766                 $pkg->{'state'} =
1767                         exists $pkg->{'failed'} ? 'Failed' : 'Building';
1768         }
1769         if (!exists $pkg->{'version'} and $pkg->{'state'} ne 'Not-For-Us') {
1770                 die "Database entry for $pkg->{'package'} lacks Version: field\n";
1771         }
1772         # check state field
1773         die "Bad state $pkg->{'state'} of package $pkg->{Package}\n"
1774                 if !isin( $pkg->{'state'},
1775                                   qw(Needs-Build Building Built Build-Attempted Uploaded Installed Dep-Wait Dep-Wait-Removed
1776                                          Failed Failed-Removed Not-For-Us BD-Uninstallable Auto-Not-For-Us
1777                                          ) );
1778 }
1779
1780 sub export_db {
1781         my $file = shift;
1782         my($name,$pkg,$key);
1783
1784         print "Writing ASCII database to $file..." if $verbose >= 1;
1785         open( my $fh, '>', $file ) or
1786                 die "Can't open export $file: $!\n";
1787
1788         my $db = get_all_source_info();
1789         foreach $name (keys %$db) {
1790                 next if $name =~ /^_/;
1791                 my $pkg = $db->{$name};
1792                 foreach $key (keys %{$pkg}) {
1793                         my $val = $pkg->{$key};
1794                         next if !defined($val);
1795                         $val =~ s/\n*$//;
1796                         $val =~ s/^/ /mg;
1797                         $val =~ s/^ +$/ ./mg;
1798                         print $fh "$key: $val\n";
1799                 }
1800                 print $fh "\n";
1801        }
1802        close( $fh );
1803        print "done\n" if $verbose >= 1;
1804 }
1805
1806 sub change_state {
1807         my $pkgr = shift;
1808         my $pkg = $$pkgr;
1809         my $newstate = shift;
1810         my $state = \$pkg->{'state'};
1811         
1812         return if defined($$state) and $$state eq $newstate;
1813         $pkg->{'previous_state'} = $$state if defined($$state);
1814         $pkg->{'state_change'} = $curr_date;
1815         $pkg->{'do_state_change'} = 1;
1816
1817         if (defined($$state) and $$state eq 'Failed') {
1818                 $pkg->{'old_failed'} =
1819                         "-"x20 . " $pkg->{'version'} " . "-"x20 . "\n" .
1820                         ($pkg->{'failed'} // ""). "\n" .
1821                         ($pkg->{'old_failed'} // "");
1822                 delete $pkg->{'failed'};
1823                 delete $pkg->{'failed_category'};
1824         }
1825         if (defined($$state) and $$state eq 'BD-Uninstallable') {
1826                 delete $pkg->{'bd_problem'};
1827         }
1828         $$state = $newstate;
1829 }
1830
1831 sub log_ta {
1832         my $pkg = shift;
1833         my $action = shift;
1834         my $dist = $distribution;
1835         my $str;
1836         my $prevstate;
1837
1838         $prevstate = $pkg->{'previous_state'};
1839         $str = "$action($dist): $pkg->{'package'}_$pkg->{'version'} ".
1840                    "changed from $prevstate to $pkg->{'state'} ".
1841                    "by $real_user as $user";
1842         
1843         if ($simulate) {
1844             printf "update transactions: %s %s %s %s %s %s %s %s\n",
1845                 $pkg->{'package'}, $distribution,
1846                 $pkg->{'version'}, $action, $prevstate, $pkg->{'state'},
1847                 $real_user, $user;
1848             return;
1849         }
1850         $dbh->do('INSERT INTO ' . transactions_table_name() .
1851                         ' (package, distribution, version, action, ' .
1852                         ' prevstate, state, real_user, set_user, time) ' .
1853                         ' values (?, ?, ?, ?, ?, ?, ?, ?, ?)',
1854                 undef, $pkg->{'package'}, $distribution,
1855                 $pkg->{'version'}, $action, $prevstate, $pkg->{'state'},
1856                 $real_user, $user, 'now()') or die $dbh->errstr;
1857
1858         if (!($prevstate eq 'Failed' && $pkg->{'state'} eq 'Failed')) {
1859                 $str .= " (with --override)"
1860                         if $opt_override;
1861                 $mail_logs .= "$str\n";
1862         }
1863 }
1864
1865
1866 sub send_mail {
1867         my $to = shift;
1868         my $subject = shift;
1869         my $text = shift;
1870
1871         my $from = $conf::db_maint;
1872         my $domain = $conf::buildd_domain;
1873
1874         $from .= "\@$domain" if $from !~ /\@/;
1875
1876         $to .= '@' . $domain if $to !~ /\@/;
1877         $text =~ s/^\.$/../mg;
1878         local $SIG{'PIPE'} = 'IGNORE';
1879         open( my $pipe,  '|-', "$conf::mailprog -oem $to" )
1880                 or die "Can't open pipe to $conf::mailprog: $!\n";
1881         chomp $text;
1882         print $pipe "From: $from\n";
1883         print $pipe "Subject: $subject\n\n";
1884         print $pipe "$text\n";
1885         close( $pipe );
1886 }
1887
1888 # for parsing input to dep-wait
1889 sub parse_deplist {
1890     my $deps = shift;
1891     my $verify = shift;
1892     my %result;
1893     
1894     foreach (split( /\s*,\s*/, $deps )) {
1895         if ($verify) {
1896             # verification requires > starting prompts, no | crap
1897             if (!/^(\S+)\s*(\(\s*(>(?:[>=])?)\s*(\S+)\s*\))?\s*$/) {
1898                 return 0;
1899             }
1900             next;
1901         }
1902         my @alts = split( /\s*\|\s*/, $_ );
1903         # Anything with an | is ignored, as it can be configured on a
1904         # per-buildd basis what will be installed
1905         next if $#alts != 0;
1906         $_ = shift @alts;
1907
1908         if (!/^(\S+)\s*(\(\s*(>=|=|==|>|>>|<<|<=)\s*(\S+)\s*\))?\s*$/) {
1909             warn( "parse_deplist: bad dependency $_\n" );
1910             next;
1911         }
1912         my($dep, $rel, $relv) = ($1, $3, $4);
1913         $rel = ">>" if defined($rel) and $rel eq ">";
1914         $result{$dep}->{'package'} = $dep;
1915         if ($rel && $relv) {
1916             $result{$dep}->{'rel'} = $rel;
1917             $result{$dep}->{'version'} = $relv;
1918         }
1919     }
1920     return 1 if $verify;
1921     return \%result;
1922 }
1923
1924 sub build_deplist {
1925         my $list = shift;
1926         my($key, $result);
1927         
1928         foreach $key (keys %$list) {
1929                 $result .= ", " if $result;
1930                 $result .= $key;
1931                 $result .= " ($list->{$key}->{'rel'} $list->{$key}->{'version'})"
1932                         if $list->{$key}->{'rel'} && $list->{$key}->{'version'};
1933         }
1934         return $result;
1935 }
1936
1937
1938 sub filterarch {
1939     return "" unless $_[0];
1940     return Dpkg::Deps::parse($_[0], ("reduce_arch" => 1, "host_arch" => $_[1]))->dump();
1941 }
1942
1943 sub wb_edos_builddebcheck {
1944 # Copyright (C) 2008 Ralf Treinen <treinen@debian.org>
1945 # This program is free software: you can redistribute it and/or modify it under
1946 # the terms of the GNU General Public License as published by the Free Software
1947 # Foundation, version 2 of the License.
1948 # integrated into wanna-builds code by Andreas Barth 2010
1949
1950     my $args = shift;
1951     my $sourceprefix="source---";
1952     my $architecture=$args->{'arch'};
1953     my $edosoptions = "-failures -explain -quiet";
1954     my $packagefiles = $args->{'pkgs'};
1955     my $sourcesfile = $args->{'src'};
1956
1957     my $packagearch="";
1958     foreach my $packagefile (@$packagefiles) {
1959         open(my $fh,'<', $packagefile);
1960         while (<$fh>) {
1961             next unless /^Architecture/;
1962             next if /^Architecture:\s*all/;
1963             /Architecture:\s*([^\s]*)/;
1964             if ($packagearch eq "") {
1965                 $packagearch = $1;
1966             } elsif ( $packagearch ne $1) {
1967                 return "Package file contains different architectures: $packagearch, $1";
1968             }
1969         }
1970         close $fh;
1971     }
1972
1973     if ( $architecture eq "" ) {
1974         if ( $packagearch eq "" ) {
1975         return "No architecture option given, " .
1976             "and no non-all architecture found in the Packages file";
1977         } else {
1978             $architecture = $packagearch;
1979         }
1980     } else {
1981         if ( $packagearch ne "" & $architecture ne $packagearch) {
1982             return "Architecture option is $architecture ".
1983             "but the package file contains architecture $packagearch";
1984         }   
1985     }
1986
1987     print "calling: edos-debcheck $edosoptions < $sourcesfile ".join('', map {" '-base FILE' ".$_ } @$packagefiles)."\n";
1988     open(my $result_cmd, '-|',
1989         "edos-debcheck $edosoptions < $sourcesfile ".join('', map {" '-base FILE' ".$_ } @$packagefiles));
1990
1991     my $explanation="";
1992     my $result={};
1993     my $binpkg="";
1994
1995     while (<$result_cmd>) {
1996 # source---pulseaudio (= 0.9.15-4.1~bpo50+1): FAILED
1997 #   source---pulseaudio (= 0.9.15-4.1~bpo50+1) depends on missing:
1998 #   - libltdl-dev (>= 2.2.6a-2)
1999 # source---libcanberra (= 0.22-1~bpo50+1): FAILED
2000 #   source---libcanberra (= 0.22-1~bpo50+1) depends on missing:
2001 #   - libltdl-dev
2002 #   - libltdl7-dev (>= 2.2.6)
2003
2004         if (/^\s+/) {
2005             s/^(\s*)$sourceprefix(.*)depends on/$1$2build-depends on/o;
2006             s/^(\s*)$sourceprefix(.*) and (.*) conflict/$1$2 build-conflicts with $3/o;
2007             $explanation .= $_;
2008         } else {
2009             if (/^$sourceprefix(.*) \(.*\): FAILED/o) {
2010                 $result->{$binpkg} = $explanation if $binpkg;
2011                 $explanation = "";
2012                 $binpkg = $1;
2013             } elsif (/^(depwait---.*) \(.*\): FAILED/o) {
2014                 $result->{$binpkg} = $explanation if $binpkg;
2015                 $explanation = "";
2016                 $binpkg = $1;
2017             } else { # else something broken is happening
2018                 #print "ignoring $_\n";
2019                 1;
2020             }
2021         }
2022     }
2023
2024     close $result_cmd;
2025     $result->{$binpkg} = $explanation if $binpkg;
2026     return $result;
2027
2028 }
2029
2030
2031 sub call_edos_depcheck {
2032     return if $simulate_edos;
2033     my $args = shift;
2034     my $srcs = $args->{'srcs'};
2035     my $key;
2036     
2037     return if defined ($distributions{$distribution}{noadw}) && not defined $args->{'depwait'};
2038
2039     # We need to check all of needs-build, as any new upload could make
2040     # something in needs-build have uninstallable deps
2041     # We also check everything in bd-uninstallable, as any new upload could
2042     # make that work again
2043     my (%interesting_packages, %interesting_packages_depwait);
2044     my $db = get_all_source_info();
2045     foreach $key (keys %$db) {
2046         my $pkg = $db->{$key};
2047         if (defined $pkg and isin($pkg->{'state'}, qw/Needs-Build BD-Uninstallable/) and not defined ($distributions{$distribution}{noadw})) {
2048                 $interesting_packages{$key} = undef;
2049         }
2050         if (defined $pkg and isin($pkg->{'state'}, qw/Dep-Wait/) and defined $args->{'depwait'}) {
2051                 $interesting_packages_depwait{$key} = undef;
2052                 # we always check for BD-Uninstallability in depwait - could be that depwait is satisfied but package is uninstallable
2053                 $interesting_packages{$key} = undef unless defined ($distributions{$distribution}{noadw});
2054         }
2055     }
2056     
2057     #print "I would look at these sources with edos-depcheck:\n";
2058     #print join " ", keys %interesting_packages,"\n";
2059     return unless %interesting_packages || %interesting_packages_depwait;
2060
2061     my $tmpfile_pattern = "/tmp/wanna-build-interesting-sources-$distribution.$$-XXXXX";
2062     use File::Temp qw/ tempfile /;
2063     my ($SOURCES, $tmpfile) = tempfile( $tmpfile_pattern, UNLINK => 1 );
2064     for my $key (keys %interesting_packages) {
2065         my $pkg = $db->{$key};
2066         # we print the source files as binary ones (with "source---"-prefixed),
2067         # so we can try if these "binary" packages are installable.
2068         # If such a "binary" package is installable, the corresponding source package is buildable.
2069         print $SOURCES "Package: source---$key\n";
2070         print $SOURCES "Version: $pkg->{'version'}\n";
2071         my $t = &filterarch($srcs->{$key}{'dep'} || $srcs->{$key}{'depends'}, $arch);
2072         my $tt = &filterarch($pkg->{'extra_depends'}, $arch);
2073         $t = $t ? ($tt ? "$t, $tt" : $t) : $tt;
2074         print $SOURCES "Depends: $t\n" if $t;
2075         my $u = &filterarch($srcs->{$key}{'conf'} || $srcs->{$key}{'conflicts'}, $arch);
2076         my $uu = &filterarch($pkg->{'extra_conflicts'}, $arch);
2077         $u = $u ? ($uu ? "$u, $uu" : $u) : $uu;
2078         print $SOURCES "Conflicts: $u\n" if $u;
2079         print $SOURCES "Architecture: all\n";
2080         print $SOURCES "\n";
2081     }
2082     for my $key (keys %interesting_packages_depwait) {
2083         my $pkg = $db->{$key};
2084         # we print the source files as binary ones (with "depwait---"-prefixed),
2085         # so we can try if these "binary" packages are installable.
2086         # If such a "binary" package is installable, the corresponding source package goes out of depwait
2087         print $SOURCES "Package: depwait---$key\n";
2088         print $SOURCES "Version: $pkg->{'version'}\n";
2089         print $SOURCES "Depends: $pkg->{'depends'}\n";
2090         print $SOURCES "Architecture: all\n";
2091         print $SOURCES "\n";
2092     }
2093     close $SOURCES;
2094
2095     my $edosresults = wb_edos_builddebcheck({'arch' => $args->{'arch'}, 'pkgs' => $args->{'pkgs'}, 'src' => $tmpfile});
2096     if (ref($edosresults) eq 'HASH') {
2097         foreach my $key (grep { $_ !~ /^depwait---/ } keys %$edosresults) {
2098                 if (exists $interesting_packages{$key}) {
2099                     $interesting_packages{$key} = $edosresults->{$key};
2100                 } else {
2101                     #print "TODO: edos reported a package we do not care about now\n" if $verbose;
2102                 }
2103         }
2104         foreach my $key (grep { $_ =~ /^depwait---/ } keys %$edosresults) {
2105                 $key =~ /^depwait---(.*)/ and $key = $1;
2106                 if (exists $interesting_packages_depwait{$key}) {
2107                     $interesting_packages_depwait{$key} = $edosresults->{"depwait---".$key};
2108                 } else {
2109                     #print "TODO: edos reported a package we do not care about now\n" if $verbose;
2110                 }
2111         }
2112     } else {
2113         # if $edosresults isn't an hash, then something went wrong and the string is the error message
2114         print "ERROR: Could not run wb-edos-builddebcheck. I am continuing, assuming\n" .
2115              "all packages have installable build-dependencies."
2116     }
2117     
2118     unlink( $tmpfile );
2119
2120     for my $key (keys %interesting_packages) {
2121         next if defined $interesting_packages_depwait{$key};
2122         my $pkg = $db->{$key};
2123         my $change = 
2124             (defined $interesting_packages{$key} and $pkg->{'state'} eq 'Needs-Build') ||
2125             (not defined $interesting_packages{$key} and $pkg->{'state'} eq 'BD-Uninstallable');
2126         my $problemchange = ($interesting_packages{$key}//"") ne ($pkg->{'bd_problem'}//"");
2127         if ($change) {
2128             if (defined $interesting_packages{$key}) {
2129                     change_state( \$pkg, 'BD-Uninstallable' );
2130                     $pkg->{'bd_problem'} = $interesting_packages{$key};
2131             } else {
2132                     change_state( \$pkg, 'Needs-Build' );
2133             }
2134         }
2135         if ($problemchange) {
2136             if (defined $interesting_packages{$key}) {
2137                     $pkg->{'bd_problem'} = $interesting_packages{$key};
2138             }   
2139         }
2140         if ($change) {
2141             log_ta( $pkg, "--merge-all (edos)" ) unless $simulate;
2142             print "edos-builddebchange changed state of ${key}_$pkg->{'version'} ($args->{'arch'}) to $pkg->{'state'}\n" if $verbose || $simulate;
2143         }
2144         if ($change || $problemchange) {
2145             update_source_info($pkg) unless $simulate;
2146         }
2147     }
2148
2149     for my $key (keys %interesting_packages_depwait) {
2150         if ($interesting_packages_depwait{$key}) {
2151             print "dep-wait for $key ($args->{'arch'}) not fullfiled yet\n" if $verbose || $simulate;
2152             next;
2153         }
2154         my $pkg = $db->{$key};
2155             if (defined $interesting_packages{$key}) {
2156                     change_state( \$pkg, 'BD-Uninstallable' );
2157                     $pkg->{'bd_problem'} = $interesting_packages{$key};
2158             } else {
2159                     change_state( \$pkg, 'Needs-Build' );
2160             }
2161         log_ta( $pkg, "edos_depcheck: depwait" ) unless $simulate;
2162         update_source_info($pkg) unless $simulate;
2163         print "edos-builddebchange changed state of ${key}_$pkg->{'version'} ($args->{'arch'}) from dep-wait to $pkg->{'state'}\n" if $verbose || $simulate;
2164     }
2165 }
2166
2167 sub usage {
2168         my $prgname;
2169         ($prgname = $0) =~ s,^.*/,,;
2170         print <<"EOF";
2171 Usage: $prgname <options...> <package_version...>
2172 Options:
2173     -v, --verbose: Verbose execution.
2174     -A arch: Architecture this operation is for.
2175     --take: Take package for building [default operation]
2176     -f, --failed: Record in database that a build failed due to
2177         deficiencies in the package (that aren't fixable without a new
2178         source version).
2179     -u, --uploaded: Record in the database that the packages build
2180         correctly and were uploaded.
2181     -n, --no-build: Record in the database that the packages aren't
2182         desired for this architecture and shouldn't appear in listings even
2183         if they're out of date.
2184     --dep-wait: Record in the database that the packages are waiting
2185         for some source dependencies to become available
2186     --binNMU num: Schedule a re-build of the package with unchanged source, but
2187          a new version number (source-version + "+b<num>")
2188     --give-back: Mark a package as ready to build that is in state Building,
2189          Built or Build-Attempted. To give back a package in state Failed, use
2190          --override. This command will actually put the package in state
2191          BD-Uninstallable, until the installability of its Build-Dependencies
2192          were verified. This happens at each call of --merge-all, usually
2193          every 15 minutes.
2194     -i SRC_PKG, --info SRC_PKG: Show information for source package
2195     -l STATE, --list=STATE: List all packages in state STATE; can be
2196         combined with -U to restrict to a specific user; STATE can
2197         also be 'all'
2198     -m MESSAGE, --message=MESSAGE: Give reason why package failed or
2199         source dependency list
2200         (used with -f, --dep-wait, and --binNMU)
2201     -o, --override: Override another user's lock on a package, i.e.
2202         take it over; a notice mail will be sent to the other user
2203     -U USER, --user=USER: select user name for which listings should
2204         apply, if not given all users are listed.
2205         if -l is missing, set user name to be entered in db; usually
2206         automatically choosen
2207     --import FILE: Import database from a ASCII file FILE
2208     --export FILE: Export database to a ASCII file FILE
2209
2210 The remaining arguments (depending on operation) usually start with
2211 "name_version", the trailer is ignored. This allows to pass the names
2212 of .dsc files, for which file name completion can be used.
2213 --merge-packages and --merge-quinn take Package/quin--diff file names
2214 on the command line or read stdin. --list needs nothing more on the
2215 command line. --info takes source package names (without version).
2216 EOF
2217         exit 1;
2218 }
2219
2220 sub pkg_version_eq {
2221         my $pkg = shift;
2222         my $version = shift;
2223
2224         return 1
2225                if (defined $pkg->{'binary_nmu_version'}) and 
2226                version_compare(binNMU_version($pkg->{'version'},
2227                         $pkg->{'binary_nmu_version'}),'=', $version);
2228         return version_compare( $pkg->{'version'}, "=", $version );
2229 }
2230
2231 sub table_name {
2232         return '"' . $arch . $schema_suffix . '".packages';
2233 }
2234
2235 sub user_table_name {
2236         return '"' . $arch . $schema_suffix . '".users';
2237 }
2238
2239 sub transactions_table_name {
2240         return '"' . $arch . $schema_suffix . '".transactions';
2241 }
2242
2243 sub pkg_history_table_name {
2244         return '"' . $arch . $schema_suffix . '".pkg_history';
2245 }
2246
2247 sub get_readonly_source_info {
2248         my $name = shift;
2249         # SELECT FLOOR(EXTRACT('epoch' FROM age(localtimestamp, '2010-01-22  23:45')) / 86400) -- change to that?
2250         my $q = "SELECT rel, priority, state_change, permbuildpri, section, buildpri, failed, state, binary_nmu_changelog, bd_problem, version, package, distribution, installed_version, notes, failed_category, builder, old_failed, previous_state, binary_nmu_version, depends, extract(days from date_trunc('days', now() - state_change)) as state_days, floor(extract(epoch from now()) - extract(epoch from state_change)) as state_time"
2251             . ", (SELECT max(build_time) FROM ".pkg_history_table_name()." WHERE pkg_history.package = packages.package AND pkg_history.distribution = packages.distribution AND result = 'successful') AS successtime"
2252             . ", (SELECT max(build_time) FROM ".pkg_history_table_name()." WHERE pkg_history.package = packages.package AND pkg_history.distribution = packages.distribution ) AS anytime"
2253             . ", extra_depends, extra_conflicts, build_arch_all"
2254             . " FROM " .  table_name()
2255             . ' WHERE package = ? AND distribution = ?';
2256         my $pkg = $dbh->selectrow_hashref( $q,
2257                 undef, $name, $distribution);
2258         return $pkg;
2259 }
2260
2261 sub get_source_info {
2262         my $name = shift;
2263         return get_readonly_source_info($name) if $simulate;
2264         my $pkg = $dbh->selectrow_hashref('SELECT *, extract(days from date_trunc(\'days\', now() - state_change)) as state_days, floor(extract(epoch from now()) - extract(epoch from state_change)) as state_time FROM ' . 
2265                 table_name() . ' WHERE package = ? AND distribution = ?' .
2266                 ' FOR UPDATE',
2267                 undef, $name, $distribution);
2268         return $pkg;
2269 }
2270
2271 sub get_all_source_info {
2272         my %options = @_;
2273
2274         my $q = "SELECT rel, priority, state_change, permbuildpri, section, buildpri, failed, state, binary_nmu_changelog, bd_problem, version, package, distribution, installed_version, notes, failed_category, builder, old_failed, previous_state, binary_nmu_version, depends, extract(days from date_trunc('days', now() - state_change)) as state_days, floor(extract(epoch from now()) - extract(epoch from state_change)) as state_time"
2275 #            . ", (SELECT max(build_time) FROM ".pkg_history_table_name()." WHERE pkg_history.package = packages.package AND pkg_history.distribution = packages.distribution AND result = 'successful') AS successtime"
2276 #            . ", (SELECT max(build_time) FROM ".pkg_history_table_name()." WHERE pkg_history.package = packages.package AND pkg_history.distribution = packages.distribution ) AS anytime"
2277             . ", successtime.build_time as successtime, anytime.build_time as anytime, extra_depends, extra_conflicts"
2278             . " FROM " .  table_name()
2279                 . " left join ( "
2280                   . "select distinct on (package, distribution) build_time, package, distribution from ".pkg_history_table_name()." where result = 'successful' order by package, distribution, timestamp "
2281                   . " ) as successtime using (package, distribution) "
2282                 . " left join ( "
2283                   . "select distinct on (package, distribution) build_time, package, distribution from ".pkg_history_table_name()." order by package, distribution, timestamp desc"
2284                   . " ) as anytime using (package, distribution) "
2285             . " WHERE TRUE ";
2286         my @args = ();
2287         if ($distribution) {
2288             my @dists = split(/[, ]+/, $distribution);
2289             $q .= ' AND ( distribution = ? '.(' OR distribution = ? ' x $#dists).' )';
2290             foreach my $d ( @dists ) {
2291                 push @args, ($d);
2292             }
2293         }
2294         if ($options{state} && uc($options{state}) ne "ALL") {
2295                 $q .= ' AND upper(state) = ? ';
2296                 push @args, uc($options{state});
2297         }
2298
2299         if ($options{user} && uc($options{state}) ne "NEEDS-BUILD") { # if it's NEEDS-BUILD, we don't look at users
2300                 #this basically means "this user, or no user at all":
2301                 $q .= " AND (builder = ? OR upper(state) = 'NEEDS-BUILD')";
2302                 push @args, $options{user};
2303         }
2304
2305         if ($options{category}) {
2306                 $q .= ' AND failed_category <> ? AND upper(state) = ? ';
2307                 push @args, $options{category};
2308                 push @args, "FAILED";
2309         }
2310
2311         if ($options{list_min_age} && $options{list_min_age} > 0) {
2312                 $q .= ' AND age(state_change) > ? ';
2313                 push @args, $options{list_min_age} . " days";
2314         }
2315
2316         if ($options{list_min_age} && $options{list_min_age} < 0) {
2317                 $q .= ' AND age(state_change) < ? ';
2318                 push @args, -$options{list_min_age} . " days";
2319         }
2320
2321         my $db = $dbh->selectall_hashref($q, 'package', undef, @args);
2322         return $db;
2323 }
2324
2325 sub show_distribution_architectures {
2326         my $q = 'SELECT distribution, spacecat_all(architecture) AS architectures '.
2327                 'FROM distribution_architectures '.
2328                 'GROUP BY distribution';
2329         my $rows = $dbh->selectall_hashref($q, 'distribution');
2330         foreach my $name (keys %$rows) {
2331                 print $name.': '.$rows->{$name}->{'architectures'}."\n";
2332         }
2333 }
2334
2335 sub show_distribution_aliases {
2336         foreach my $alias (keys %distribution_aliases) {
2337                 print $alias.': '.$distribution_aliases{$alias}."\n";
2338         }
2339 }
2340
2341 sub update_source_info {
2342         my $pkg = shift;
2343         $pkg->{'extra_depends'} = $extra_depends if defined $extra_depends;
2344         undef $pkg->{'extra_depends'} unless $pkg->{'extra_depends'};
2345         $pkg->{'extra_conflicts'} = $extra_conflicts if defined $extra_conflicts;
2346         undef $pkg->{'extra_conflicts'} unless $pkg->{'extra_conflicts'};
2347         print Dumper $pkg if $verbose and $simulate;
2348         return if $simulate;
2349
2350         my $pkg2 = get_source_info($pkg->{'package'});
2351         if (! defined $pkg2)
2352         {
2353                 add_source_info($pkg);
2354         }
2355
2356         $dbh->do('UPDATE ' . table_name() . ' SET ' .
2357                         'version = ?, ' .
2358                         'state = ?, ' .
2359                         'section = ?, ' .
2360                         'priority = ?, ' .
2361                         'installed_version = ?, ' .
2362                         'previous_state = ?, ' .
2363                         (($pkg->{'do_state_change'}) ? "state_change = now()," : "").
2364                         'notes = ?, ' .
2365                         'builder = ?, ' .
2366                         'failed = ?, ' .
2367                         'old_failed = ?, ' .
2368                         'binary_nmu_version = ?, ' .
2369                         'binary_nmu_changelog = ?, ' .
2370                         'failed_category = ?, ' .
2371                         'permbuildpri = ?, ' .
2372                         'buildpri = ?, ' .
2373                         'depends = ?, ' .
2374                         'rel = ?, ' .
2375                         'extra_depends = ?, ' .
2376                         'extra_conflicts = ?, ' .
2377                         'bd_problem = ? ' .
2378                         'WHERE package = ? AND distribution = ?',
2379                 undef,
2380                 $pkg->{'version'},
2381                 $pkg->{'state'},
2382                 $pkg->{'section'},
2383                 $pkg->{'priority'},
2384                 $pkg->{'installed_version'},
2385                 $pkg->{'previous_state'},
2386                 $pkg->{'notes'},
2387                 $pkg->{'builder'},
2388                 $pkg->{'failed'},
2389                 $pkg->{'old_failed'},
2390                 $pkg->{'binary_nmu_version'},
2391                 $pkg->{'binary_nmu_changelog'},
2392                 $pkg->{'failed_category'},
2393                 $pkg->{'permbuildpri'},
2394                 $pkg->{'buildpri'},
2395                 $pkg->{'depends'},
2396                 $pkg->{'rel'},
2397                 $pkg->{'extra_depends'},
2398                 $pkg->{'extra_conflicts'},
2399                 $pkg->{'bd_problem'},
2400                 $pkg->{'package'},
2401                 $distribution) or die $dbh->errstr;
2402 }
2403
2404 sub add_source_info {
2405         return if $simulate;
2406         my $pkg = shift;
2407         $dbh->do('INSERT INTO ' . table_name() .
2408                         ' (package, distribution) values (?, ?)',
2409                 undef, $pkg->{'package'}, $distribution) or die $dbh->errstr;
2410 }
2411
2412 sub del_source_info {
2413         return if $simulate;
2414         my $name = shift;
2415         $dbh->do('DELETE FROM ' . table_name() .
2416                         ' WHERE package = ? AND distribution = ?',
2417                 undef, $name, $distribution) or die $dbh->errstr;
2418 }
2419
2420 sub get_user_info {
2421         my $name = shift;
2422         my $user = $dbh->selectrow_hashref('SELECT * FROM ' . 
2423                 user_table_name() . ' WHERE username = ? AND distribution = ?',
2424                 undef, $name, $distribution);
2425         return $user;
2426 }
2427
2428 sub update_user_info {
2429         return if $simulate;
2430         my $user = shift;
2431         $dbh->do('UPDATE ' . user_table_name() .
2432                         ' SET last_seen = now() WHERE username = ?' .
2433                         ' AND distribution = ?',
2434                 undef, $user, $distribution)
2435                 or die $dbh->errstr;
2436 }
2437
2438
2439 sub add_user_info {
2440         return if $simulate;
2441         my $user = shift;
2442         $dbh->do('INSERT INTO ' . user_table_name() .
2443                         ' (username, distribution, last_seen)' .
2444                         ' values (?, ?, now())',
2445                 undef, $user, $distribution)
2446                 or die $dbh->errstr;
2447 }
2448
2449 sub lock_table {
2450         return if $simulate;
2451         $dbh->do('LOCK TABLE ' . table_name() .
2452                 ' IN EXCLUSIVE MODE', undef) or die $dbh->errstr;
2453 }
2454
2455 sub parse_argv {
2456 # parts the array $_[0] and $_[1] and returns the sub-array (modifies the original one)
2457     my @ret = ();
2458     my $args = shift;
2459     my $separator = shift;
2460     while($args->[0] && $args->[0] ne $separator) { 
2461         push @ret, shift @$args;
2462     }
2463     shift @$args if @$args;
2464     return @ret;
2465 }
2466
2467 sub parse_all_v3 {
2468     my $srcs = shift;
2469     my $vars = shift;
2470     my $db = get_all_source_info();
2471     my $binary = $srcs->{'_binary'};
2472
2473     SRCS:
2474     foreach my $name (keys %$srcs) {
2475         next if $name eq '_binary';
2476
2477         # state = installed, out-of-date, uncompiled, not-for-us, auto-not-for-us
2478         my $pkgs = $srcs->{$name};
2479         my $pkg = $db->{$name};
2480
2481         unless ($pkg) {
2482             next SRCS if $pkgs->{'status'} eq 'not-for-us';
2483             my $logstr = sprintf("merge-v3 %s %s_%s (%s, %s):", $vars->{'time'}, $name, $pkgs->{'version'}, $vars->{'arch'}, $vars->{'suite'});
2484
2485             # does at least one binary exist in the database and is more recent - if so, we're probably just outdated, ignore the source package
2486             for my $bin (@{$pkgs->{'binary'}}) {
2487                 if ($binary->{$bin} and vercmp($pkgs->{'version'}, $binary->{$bin}->{'version'}) < 0) {
2488                     print "$logstr skipped because binaries (assumed to be) overwritten\n" if $verbose || $simulate;
2489                     next SRCS;
2490                 }
2491             }
2492             $pkg->{'package'}  = $name;
2493         }
2494         my $logstr = sprintf("merge-v3 %s %s_%s", $vars->{'time'}, $name, $pkgs->{'version'}).
2495             ($pkgs->{'binnmu'} ? ";b".$pkgs->{'binnmu'} : "").
2496             sprintf(" (%s, %s, previous: %s", $vars->{'arch'}, $vars->{'suite'}, $pkg->{'version'}//"").
2497             ($pkg->{'binary_nmu_version'} ? ";b".$pkg->{'binary_nmu_version'} : "").
2498             ", $pkg->{'state'}):";
2499
2500         if (isin($pkgs->{'status'}, qw (installed related)) && $pkgs->{'version'} eq $pkg->{'version'} && ($pkgs->{'binnmu'}//0) < int($pkg->{'binary_nmu_version'}//0)) {
2501                 $pkgs->{'status'} = 'out-of-date';
2502         }
2503         if (isin($pkgs->{'status'}, qw (installed related auto-not-for-us))) {
2504             my $change = 0;
2505             my $tstate = {'installed' => 'Installed', 'related' => 'Installed', 'auto-not-for-us' => 'Auto-Not-For-Us'}->{$pkgs->{'status'}};
2506             next if isin( $pkg->{'state'}, qw<Not-For-Us Failed Failed-Removed Dep-Wait Dep-Wait-Removed>) && isin( $tstate, qw<Auto-Not-For-Us>);
2507             # if the package is currently current, the status is Installed, not not-for-us
2508             if ($pkg->{'state'} ne $tstate) {
2509                 change_state( \$pkg, $tstate);
2510                 if (isin( $tstate, qw<Installed>)) {
2511                     delete $pkg->{'depends'};
2512                     delete $pkg->{'extra_depends'};
2513                     delete $pkg->{'extra_conflicts'};
2514                 }
2515                 $change++;
2516             }
2517             my $attrs = { 'version' => 'version', 'installed_version' => 'version', 'binary_nmu_version' => 'binnmu', 'section' => 'section', 'priority' => 'priority' };
2518             foreach my $k (keys %$attrs) {
2519                 next if isin( $tstate, qw<Auto-Not-For-Us>) && isin( $k, qw<installed_version binary_nmu_version>);
2520                 if (($pkg->{$k}//"") ne ($pkgs->{$attrs->{$k}}//"")) {
2521                     $pkg->{$k} = $pkgs->{$attrs->{$k}};
2522                     $change++;
2523                 }
2524             }
2525             if (isin($pkgs->{'status'}, qw (related)) and $pkg->{'notes'} ne "related") {
2526                 $pkg->{'notes'} = "related";
2527                 $change++;
2528             }
2529             if ($change) {
2530                 print "$logstr set to $tstate/".($pkg->{'notes'}//"")."\n" if $verbose || $simulate;
2531                 log_ta( $pkg, "--merge-v3: $tstate" ) unless $simulate;
2532                 update_source_info($pkg) unless $simulate;
2533             }
2534             next;
2535         }
2536
2537         if ($pkgs->{'status'} eq 'not-for-us') {
2538             next if isin( $pkg->{'state'}, qw(Not-For-Us Installed Failed-Removed));
2539
2540             if (isin( $pkg->{'state'}, qw(Failed Build-Attempted Built))) {
2541                 change_state( \$pkg, "Failed-Removed" );
2542                 log_ta( $pkg, "--merge-v3: Failed-Removed" ) unless $simulate;
2543                 update_source_info($pkg) unless $simulate;
2544                 print "$logstr (virtually) deleted from database\n" if $verbose || $simulate;
2545                 next;
2546             }
2547
2548             print "$logstr should delete (not-for-us according to P-a-s)\n" if $verbose || $simulate || 1; # not implemented yet on purpose
2549             next;
2550         }
2551
2552         # only uncompiled / out-of-date are left, so check if anything new
2553         if (!(isin($pkgs->{'status'}, qw (uncompiled out-of-date)))) {
2554             print "$logstr package in unknown state: $pkgs->{'status'}\n";
2555             next SRCS;
2556         }
2557         next if $pkgs->{'version'} eq $pkg->{'version'} and $pkgs->{'binnmu'}//0 >= int($pkg->{'binary_nmu_version'}//0);
2558         next if $pkgs->{'version'} eq $pkg->{'version'} and !isin( $pkg->{'state'}, qw(Installed));
2559         next if isin( $pkg->{'state'}, qw(Not-For-Us Failed-Removed));
2560
2561         if (defined( $pkg->{'state'} ) && isin( $pkg->{'state'}, qw(Building Built Build-Attempted))) {
2562             send_mail( $pkg->{'builder'},
2563                 "new version of $name (dist=$distribution)",
2564                 "As far as I'm informed, you're currently building the package $name\n".
2565                 "in version $pkg->{'version'}.\n\n".
2566                 "Now there's a new source version $pkgs->{'version'}. If you haven't finished\n".
2567                 "compiling $name yet, you can stop it to save some work.\n".
2568                 "Just to inform you...\n".
2569                 "(This is an automated message)\n" ) unless $simulate;
2570             print "$logstr new version while building $pkg->{'version'} -- sending mail to builder ($pkg->{'builder'})\n"
2571                                   if $verbose || $simulate;
2572             }
2573         change_state( \$pkg, 'Needs-Build');
2574         $pkg->{'notes'} = $pkgs->{'status'};
2575         $pkg->{'version'} = $pkgs->{'version'};
2576         $pkg->{'section'} = $pkgs->{'section'};
2577         $pkg->{'priority'} = $pkgs->{'priority'};
2578         $pkg->{'dep'} = $pkgs->{'depends'};
2579         $pkg->{'conf'} = $pkgs->{'conflicts'};
2580         delete $pkg->{'builder'};
2581         delete $pkg->{'binary_nmu_version'} unless $pkgs->{'binnmu'};
2582         delete $pkg->{'binary_nmu_changelog'} unless $pkgs->{'binnmu'};
2583         log_ta( $pkg, "--merge-v3: needs-build" ) unless $simulate;
2584         update_source_info($pkg) unless $simulate;
2585         print "$logstr set to needs-builds\n" if $simulate || $verbose;
2586     }
2587
2588     foreach my $name (keys %$db) {
2589         next if $srcs->{$name};
2590         my $pkg = $db->{$name};
2591         my $logstr = "merge-v3 $vars->{'time'} ".$name."_$pkg->{'version'} ($vars->{'arch'}, $vars->{'suite'}, previous: $pkg->{'state'}):";
2592         # package disappeared - delete
2593         change_state( \$pkg, 'deleted' );
2594         log_ta( $pkg, "--merge-v3: deleted" ) unless $simulate;
2595         print "$logstr deleted from database\n" if $verbose || $simulate;
2596         del_source_info($name) unless $simulate;
2597         delete $db->{$name};
2598     }
2599 }