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