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