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