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