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