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