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