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