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