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