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