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