]> git.donarmstrong.com Git - wannabuild.git/blob - bin/wanna-build
ddea1db6e460f7f0ba3fcaec2e9b0707cc721165
[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)) {
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'}}; }],
1448         's' => ['<=>', sub { return $sectval{$_[0]->{'section'}}; }],
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 $prioval{$_[0]->{'priority'}} > $prioval{'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) <=> &{$map_funcs->{$letter}[1]}($a) if $map_funcs->{$letter}[0] eq '<->';
1460             $r = &{$map_funcs->{$letter}[1]}($a) <=> &{$map_funcs->{$letter}[1]}($b) 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             my $c = "$pkg->{'priority'}:$pkg->{'notes'}";
1590             $c .= ":PREV-FAILED" if $pkg->{'previous_state'} && $pkg->{'previous_state'} =~ /^Failed/;
1591             $c .= ":bp{" . $pkg->{'buildpri'} . "}" if defined $pkg->{'buildpri'};
1592             $c .= ":binNMU{" . $pkg->{'binary_nmu_version'} . "}" if defined $pkg->{'binary_nmu_version'};
1593             $c .= ":calprio{". $pkg->{'calprio'}."}";
1594             $c .= ":days{". $pkg->{'state_days'}."}";
1595             return $c;
1596             }, $pkg, $var),
1597         'c' => make_fmt( $pkg->{'section'}, $pkg, $var),
1598         'P' => make_fmt( $pkg->{'previous_state'} || "unknwon", $pkg, $var),
1599         'E' => make_fmt( sub { return $pkg->{'depends'} if $pkg->{'state'} eq "Dep-Wait";
1600             return $var->{scnt}{'Needs-Build'} + 1 if $pkg->{'state'} eq 'Needs-Build';
1601             return ""; }, $pkg, $var),
1602         'F' => make_fmt( sub { return "" unless $pkg->{'failed'};
1603             my $failed = $pkg->{'failed'};
1604             $failed =~ s/\\/\\\\/g;
1605             return $pkg->{'package'}."#".$arch."-failure\n ".
1606             join("\\0a",split("\n",$failed))."\\0a\n"; }, $pkg, $var),
1607         'D' => make_fmt( sub { return "" unless $pkg->{'bd_problem'};
1608             return $pkg->{'package'}."#".$arch."-bd-problem\n".
1609             join("\\0a",split("\n",$pkg->{'bd_problem'}))."\\0a\n"; }, $pkg, $var),
1610         'B' => make_fmt( sub { return $pkg->{'binary_nmu_version'} if defined $pkg->{'binary_nmu_version'}; }, $pkg, $var),
1611         'd' => make_fmt( $pkg->{'distribution'}, $pkg, $var),
1612         't' => make_fmt( $pkg->{'state_change'}, $pkg, $var),
1613         'T' => make_fmt( sub { return seconds2time(time() - floor(str2time($pkg->{'state_change'}))); }, $pkg, $var),
1614         'o' => make_fmt( $pkg->{'successtime'}, $pkg, $var),
1615         'O' => make_fmt( sub { return seconds2time ( $pkg->{'successtime'}); }, $pkg, $var),
1616         'q' => make_fmt( $pkg->{'anytime'}, $pkg, $var),
1617         'Q' => make_fmt( sub { return seconds2time ( $pkg->{'anytime'}); }, $pkg, $var),
1618         'r' => make_fmt( sub { my $c = max($pkg->{'successtime'}//0, $pkg->{'anytime'}//0); return $c if $c; return; }, $pkg, $var),
1619         'R' => make_fmt( sub { return seconds2time ( max($pkg->{'successtime'}//0, $pkg->{'anytime'}//0)); }, $pkg, $var),
1620     ));
1621 }
1622
1623 sub list_packages {
1624         my $state = shift;
1625         my( $name, $pkg, @list );
1626         my $cnt = 0;
1627         my %scnt;
1628         my $ctime = time;
1629
1630         my $db = get_all_source_info(state => $state, user => $user, category => $category, list_min_age => $list_min_age);
1631         foreach $name (keys %$db) {
1632                 next if $name =~ /^_/;
1633                 push @list, calculate_prio($db->{$name});
1634         }
1635
1636         # filter components
1637         @list = grep { my $i = $_->{'component'}; grep { $i eq $_ } split /[, ]+/, $yamlmap->{"restrict"}{'component'} } @list;
1638         # extra depends / conflicts only from api 1 on
1639         @list = grep { !$_->{'extra_depends'} and !$_->{'extra_conflicts'} } @list if $api < 1 ;
1640
1641         # first adjust ownprintformat, then set printformat accordingly
1642         $printformat ||= $yamlmap->{"format"}{$ownprintformat} if $ownprintformat;
1643         $printformat ||= $yamlmap->{"format"}{"default"}{$state};
1644         $printformat ||= $yamlmap->{"format"}{"default"}{"default"};
1645         undef $printformat if ($ownprintformat && $ownprintformat eq 'none');
1646
1647         foreach $pkg (sort sort_list_func @list) {
1648                 if ($printformat) {
1649                     print print_format($printformat, $pkg, {'cnt' => $cnt, 'scnt' => \%scnt})."\n";
1650                     ++$cnt;
1651                     $scnt{$pkg->{'state'}}++;
1652                     next;
1653                 }
1654                 print print_format("%c/%p_%v", $pkg, {});
1655                 print print_format(": %S", $pkg, {})
1656                         if $state eq "all";
1657                 print print_format("%{ by }u%u", $pkg, {})
1658                         if $pkg->{'state'} ne "Needs-Build";
1659                 print print_format(" [%X]\n", $pkg, {});
1660                 print "  Reasons for failing:\n",
1661                           "    [Category: ",
1662                           defined $pkg->{'failed_category'} ? $pkg->{'failed_category'} : "none",
1663                           "]\n    ",
1664                           join("\n    ",split("\n",$pkg->{'failed'})), "\n"
1665                         if $pkg->{'state'} =~ /^Failed/;
1666                 print "  Dependencies: $pkg->{'depends'}\n"
1667                         if $pkg->{'state'} eq "Dep-Wait";
1668                 print "  Reasons for BD-Uninstallable:\n    ",
1669                           join("\n    ",split("\n",$pkg->{'bd_problem'})), "\n"
1670                         if $pkg->{'state'} eq "BD-Uninstallable";
1671                 print "  Previous state was $pkg->{'previous_state'}\n"
1672                         if $verbose && $pkg->{'previous_state'};
1673                 print "  No previous state recorded\n"
1674                         if $verbose && !$pkg->{'previous_state'};
1675                 print "  State changed at $pkg->{'state_change'}\n"
1676                         if $verbose && $pkg->{'state_change'};
1677                 print "  Previous state $pkg->{'previous_state'} left $pkg->{'state_time'} ago\n"
1678                         if $verbose && $pkg->{'previous_state'};
1679                 print "  Previous failing reasons:\n    ",
1680                       join("\n    ",split("\n",$pkg->{'old_failed'})), "\n"
1681                         if $verbose && $pkg->{'old_failed'};
1682                 ++$cnt;
1683                 $scnt{$pkg->{'state'}}++ if $state eq "all";
1684         }
1685         if ($state eq "all" && !$printformat) {
1686                 foreach (sort keys %scnt) {
1687                         print "Total $scnt{$_} package(s) in state $_.\n";
1688                 }
1689         }
1690         print "Total $cnt package(s)\n" unless $printformat;
1691         
1692 }
1693
1694 sub info_packages {
1695         my( $name, $pkg, $key, $dist );
1696         my @firstkeys = qw(package version builder state section priority
1697                                            installed_version previous_state state_change);
1698         my @dists = $info_all_dists ? keys %distributions : ($distribution);
1699         my %beautykeys = ( 'package' => 'Package', 'version' => 'Version', 'builder' => 'Builder',
1700                 'state' => 'State', 'section' => 'Section', 'priority' => 'Priority',
1701                 'installed_version' => 'Installed-Version', 'previous_state' => 'Previous-State',
1702                 'state_change' => 'State-Change',
1703                 'bd_problem' => 'BD-Problem', 
1704                 'binary_nmu_changelog' => 'Binary-NMU-Changelog', 'binary_nmu_version' => 'Binary-NMU-Version',
1705                 'buildpri' => 'BuildPri', 'depends' => 'Depends', 'failed' => 'Failed',
1706                 'failed_category' => 'Failed-Category', 'notes' => 'Notes',
1707                 'distribution' => 'Distribution', 'old_failed' => 'Old-Failed',
1708                 'permbuildpri' => 'PermBuildPri', 'rel' => 'Rel',
1709                 'calprio' => 'CalculatedPri', 'state_days' => 'State-Days', 'state_time' => 'State-Time',
1710                 'successtime' => 'Success-build-time',
1711                 'anytime' => 'Build-time',
1712                 'extra_depends' => 'Extra-Dependencies',
1713                 'extra_conflicts' => 'Extra-Conflicts',
1714                 'build_arch_all' => 'Build-Arch-All',
1715                          );
1716         
1717         foreach $name (@_) {
1718                 $name =~ s/_.*$//; # strip version
1719                 foreach $dist (@dists) {
1720                         my $pname = "$name" . ($info_all_dists ? "($dist)" : "");
1721                         
1722                         $pkg = get_readonly_source_info($name);
1723                         if (!defined( $pkg )) {
1724                                 print "$pname: not registered\n";
1725                                 next;
1726                         }
1727                         $pkg = calculate_prio($pkg);
1728
1729                         print "$pname:\n";
1730                         foreach $key (@firstkeys) {
1731                                 next if !defined $pkg->{$key};
1732                                 my $val = $pkg->{$key};
1733                                 chomp( $val );
1734                                 $val = "\n$val" if isin( $key, qw(Failed Old-Failed));
1735                                 $val =~ s/\n/\n    /g;
1736                                 my $print_key = $key;
1737                                 $print_key = $beautykeys{$print_key} if $beautykeys{$print_key};
1738                                 printf "  %-20s: %s\n", $print_key, $val;
1739                         }
1740                         foreach $key (sort keys %$pkg) {
1741                                 next if isin( $key, @firstkeys );
1742                                 my $val = $pkg->{$key};
1743                                 next if !defined($val);
1744                                 chomp( $val );
1745                                 $val = "\n$val" if isin( $key, qw(Failed Old-Failed));
1746                                 $val =~ s/\n/\n    /g;
1747                                 my $print_key = $key;
1748                                 $print_key = $beautykeys{$print_key} if $beautykeys{$print_key};
1749                                 printf "  %-20s: %s\n", $print_key, $val;
1750                         }
1751                 }
1752         }
1753 }
1754
1755 sub forget_packages {
1756         my( $name, $pkg, $key, $data );
1757         
1758         foreach $name (@_) {
1759                 $name =~ s/_.*$//; # strip version
1760                 $pkg = get_source_info($name);
1761                 if (!defined( $pkg )) {
1762                         print "$name: not registered\n";
1763                         next;
1764                 }
1765
1766                 $data = "";
1767                 foreach $key (sort keys %$pkg) {
1768                         my $val = $pkg->{$key};
1769                         chomp( $val );
1770                         $val =~ s/\n/\n /g;
1771                         $data .= sprintf "  %-20s: %s\n", $key, $val;
1772                 }
1773                 send_mail( $conf::db_maint,
1774                                    "$name deleted from DB " . table_name() . " " . $distribution,
1775                                    "The package '$name' has been deleted from the database ".
1776                                    "by $user.\n\n".
1777                                    "Data registered about the deleted package:\n".
1778                                    "$data\n" ) if $conf::db_maint;
1779                 change_state( \$pkg, 'deleted' );
1780                 log_ta( $pkg, "--forget" );
1781                 del_source_info($name);
1782                 print "$name: deleted from database\n" if $verbose;
1783         }
1784 }
1785
1786 sub forget_users {
1787         $dbh->do("DELETE from " . user_table_name() . 
1788                 " WHERE distribution = ?", undef, $distribution) or die $dbh->errstr;
1789 }
1790
1791 sub read_db {
1792         my $file = shift;
1793
1794         print "Reading ASCII database from $file..." if $verbose >= 1;
1795         open( my $fh, '<', $file ) or
1796                 die "Can't open database $file: $!\n";
1797
1798         local($/) = ""; # read in paragraph mode
1799         while( <$fh> ) {
1800                 my( %thispkg, $name );
1801                 s/[\s\n]+$//;
1802                 s/\n[ \t]+/\376\377/g;  # fix continuation lines
1803                 s/\376\377\s*\376\377/\376\377/og;
1804   
1805                 while( /^(\S+):[ \t]*(.*)[ \t]*$/mg ) {
1806                         my ($key, $val) = ($1, $2);
1807                         $key =~ s/-/_/g;
1808                         $key =~ tr/A-Z/a-z/;
1809                         $val =~ s/\376\377/\n/g;
1810                         $thispkg{$key} = $val;
1811                 }
1812                 check_entry( \%thispkg );
1813                 # add to db
1814                 if (exists($thispkg{'package'})) {
1815                         update_source_info(\%thispkg);
1816                 }
1817                 elsif(exists($thispkg{'user'})) {
1818                         # user in import, username in database.
1819                         $dbh->do('INSERT INTO ' . user_table_name() .
1820                                         ' (username, distribution, last_seen)' .
1821                                         ' values (?, ?, ?)',
1822                                 undef, $thispkg{'user'}, $distribution,
1823                                 $thispkg{'last_seen'})
1824                                 or die $dbh->errstr;
1825                  }
1826         }
1827         close( $fh );
1828         print "done\n" if $verbose >= 1;
1829 }
1830
1831 sub check_entry {
1832         my $pkg = shift;
1833         my $field;
1834
1835         return if $op_mode eq "manual-edit"; # no checks then
1836         
1837         # check for required fields
1838         if (exists $pkg->{'user'}) {
1839                 return;
1840         }
1841         if (!exists $pkg->{'package'}) {
1842                 print STDERR "Bad entry: ",
1843                           join( "\n", map { "$_: $pkg->{$_}" } keys %$pkg ), "\n";
1844                 die "Database entry lacks package or username field\n";
1845         }
1846         # if no State: field, generate one (for old db compat)
1847         if (!exists($pkg->{'state'})) {
1848                 $pkg->{'state'} =
1849                         exists $pkg->{'failed'} ? 'Failed' : 'Building';
1850         }
1851         if (!exists $pkg->{'version'} and $pkg->{'state'} ne 'Not-For-Us') {
1852                 die "Database entry for $pkg->{'package'} lacks Version: field\n";
1853         }
1854         # check state field
1855         die "Bad state $pkg->{'state'} of package $pkg->{Package}\n"
1856                 if !isin( $pkg->{'state'},
1857                                   qw(Needs-Build Building Built Build-Attempted Uploaded Installed Dep-Wait Dep-Wait-Removed
1858                                          Failed Failed-Removed Not-For-Us BD-Uninstallable Auto-Not-For-Us
1859                                          ) );
1860 }
1861
1862 sub export_db {
1863         my $file = shift;
1864         my($name,$pkg,$key);
1865
1866         print "Writing ASCII database to $file..." if $verbose >= 1;
1867         open( my $fh, '>', $file ) or
1868                 die "Can't open export $file: $!\n";
1869
1870         my $db = get_all_source_info();
1871         foreach $name (keys %$db) {
1872                 next if $name =~ /^_/;
1873                 my $pkg = $db->{$name};
1874                 foreach $key (keys %{$pkg}) {
1875                         my $val = $pkg->{$key};
1876                         next if !defined($val);
1877                         $val =~ s/\n*$//;
1878                         $val =~ s/^/ /mg;
1879                         $val =~ s/^ +$/ ./mg;
1880                         print $fh "$key: $val\n";
1881                 }
1882                 print $fh "\n";
1883        }
1884        close( $fh );
1885        print "done\n" if $verbose >= 1;
1886 }
1887
1888 sub change_state {
1889         my $pkgr = shift;
1890         my $pkg = $$pkgr;
1891         my $newstate = shift;
1892         my $state = \$pkg->{'state'};
1893         
1894         return if defined($$state) and $$state eq $newstate;
1895         $pkg->{'previous_state'} = $$state if defined($$state);
1896         $pkg->{'state_change'} = $curr_date;
1897         $pkg->{'do_state_change'} = 1;
1898
1899         if (defined($$state) and $$state eq 'Failed') {
1900                 $pkg->{'old_failed'} =
1901                         "-"x20 . " $pkg->{'version'} " . "-"x20 . "\n" .
1902                         ($pkg->{'failed'} // ""). "\n" .
1903                         ($pkg->{'old_failed'} // "");
1904                 delete $pkg->{'failed'};
1905                 delete $pkg->{'failed_category'};
1906         }
1907         if (defined($$state) and $$state eq 'BD-Uninstallable') {
1908                 delete $pkg->{'bd_problem'};
1909         }
1910         $$state = $newstate;
1911 }
1912
1913 sub log_ta {
1914         my $pkg = shift;
1915         my $action = shift;
1916         my $dist = $distribution;
1917         my $str;
1918         my $prevstate;
1919
1920         $prevstate = $pkg->{'previous_state'};
1921         $str = "$action($dist): $pkg->{'package'}_$pkg->{'version'} ".
1922                    "changed from $prevstate to $pkg->{'state'} ".
1923                    "by $real_user as $user";
1924         
1925         if ($simulate) {
1926             printf "update transactions: %s %s %s %s %s %s %s %s\n",
1927                 $pkg->{'package'}, $distribution,
1928                 $pkg->{'version'}, $action, $prevstate, $pkg->{'state'},
1929                 $real_user, $user;
1930             return;
1931         }
1932         $dbh->do('INSERT INTO ' . transactions_table_name() .
1933                         ' (package, distribution, version, action, ' .
1934                         ' prevstate, state, real_user, set_user, time) ' .
1935                         ' values (?, ?, ?, ?, ?, ?, ?, ?, ?)',
1936                 undef, $pkg->{'package'}, $distribution,
1937                 $pkg->{'version'}, $action, $prevstate, $pkg->{'state'},
1938                 $real_user, $user, 'now()') or die $dbh->errstr;
1939
1940         if (!($prevstate eq 'Failed' && $pkg->{'state'} eq 'Failed')) {
1941                 $str .= " (with --override)"
1942                         if $opt_override;
1943                 $mail_logs .= "$str\n";
1944         }
1945 }
1946
1947
1948 sub send_mail {
1949         my $to = shift;
1950         my $subject = shift;
1951         my $text = shift;
1952
1953         my $from = $conf::db_maint;
1954         my $domain = $conf::buildd_domain;
1955
1956         $from .= "\@$domain" if $from !~ /\@/;
1957
1958         $to .= '@' . $domain if $to !~ /\@/;
1959         $text =~ s/^\.$/../mg;
1960         local $SIG{'PIPE'} = 'IGNORE';
1961         open( my $pipe,  '|-', "$conf::mailprog -oem $to" )
1962                 or die "Can't open pipe to $conf::mailprog: $!\n";
1963         chomp $text;
1964         print $pipe "From: $from\n";
1965         print $pipe "Subject: $subject\n\n";
1966         print $pipe "$text\n";
1967         close( $pipe );
1968 }
1969
1970 # for parsing input to dep-wait
1971 sub parse_deplist {
1972     my $deps = shift;
1973     my $verify = shift;
1974     my %result;
1975     
1976     foreach (split( /\s*,\s*/, $deps )) {
1977         if ($verify) {
1978             # verification requires > starting prompts, no | crap
1979             if (!/^(\S+)\s*(\(\s*(>(?:[>=])?)\s*(\S+)\s*\))?\s*$/) {
1980                 return 0;
1981             }
1982             next;
1983         }
1984         my @alts = split( /\s*\|\s*/, $_ );
1985         # Anything with an | is ignored, as it can be configured on a
1986         # per-buildd basis what will be installed
1987         next if $#alts != 0;
1988         $_ = shift @alts;
1989
1990         if (!/^(\S+)\s*(\(\s*(>=|=|==|>|>>|<<|<=)\s*(\S+)\s*\))?\s*$/) {
1991             warn( "parse_deplist: bad dependency $_\n" );
1992             next;
1993         }
1994         my($dep, $rel, $relv) = ($1, $3, $4);
1995         $rel = ">>" if defined($rel) and $rel eq ">";
1996         $result{$dep}->{'package'} = $dep;
1997         if ($rel && $relv) {
1998             $result{$dep}->{'rel'} = $rel;
1999             $result{$dep}->{'version'} = $relv;
2000         }
2001     }
2002     return 1 if $verify;
2003     return \%result;
2004 }
2005
2006 sub build_deplist {
2007         my $list = shift;
2008         my($key, $result);
2009         
2010         foreach $key (keys %$list) {
2011                 $result .= ", " if $result;
2012                 $result .= $key;
2013                 $result .= " ($list->{$key}->{'rel'} $list->{$key}->{'version'})"
2014                         if $list->{$key}->{'rel'} && $list->{$key}->{'version'};
2015         }
2016         return $result;
2017 }
2018
2019
2020 sub filterarch {
2021     return "" unless $_[0];
2022     return Dpkg::Deps::parse($_[0], ("reduce_arch" => 1, "host_arch" => $_[1]))->dump();
2023 }
2024
2025 sub wb_edos_builddebcheck {
2026 # Copyright (C) 2008 Ralf Treinen <treinen@debian.org>
2027 # This program is free software: you can redistribute it and/or modify it under
2028 # the terms of the GNU General Public License as published by the Free Software
2029 # Foundation, version 2 of the License.
2030 # integrated into wanna-builds code by Andreas Barth 2010
2031
2032     my $args = shift;
2033     my $sourceprefix="source---";
2034     my $architecture=$args->{'arch'};
2035     my $edosoptions = "-failures -explain -quiet";
2036     my $packagefiles = $args->{'pkgs'};
2037     my $sourcesfile = $args->{'src'};
2038
2039     my $packagearch="";
2040     foreach my $packagefile (@$packagefiles) {
2041         open(my $fh,'<', $packagefile);
2042         while (<$fh>) {
2043             next unless /^Architecture/;
2044             next if /^Architecture:\s*all/;
2045             /Architecture:\s*([^\s]*)/;
2046             if ($packagearch eq "") {
2047                 $packagearch = $1;
2048             } elsif ( $packagearch ne $1) {
2049                 return "Package file contains different architectures: $packagearch, $1";
2050             }
2051         }
2052         close $fh;
2053     }
2054
2055     if ( $architecture eq "" ) {
2056         if ( $packagearch eq "" ) {
2057         return "No architecture option given, " .
2058             "and no non-all architecture found in the Packages file";
2059         } else {
2060             $architecture = $packagearch;
2061         }
2062     } else {
2063         if ( $packagearch ne "" & $architecture ne $packagearch) {
2064             return "Architecture option is $architecture ".
2065             "but the package file contains architecture $packagearch";
2066         }   
2067     }
2068
2069     print "calling: edos-debcheck $edosoptions < $sourcesfile ".join('', map {" '-base FILE' ".$_ } @$packagefiles)."\n";
2070     open(my $result_cmd, '-|',
2071         "edos-debcheck $edosoptions < $sourcesfile ".join('', map {" '-base FILE' ".$_ } @$packagefiles));
2072
2073     my $explanation="";
2074     my $result={};
2075     my $binpkg="";
2076
2077     while (<$result_cmd>) {
2078 # source---pulseaudio (= 0.9.15-4.1~bpo50+1): FAILED
2079 #   source---pulseaudio (= 0.9.15-4.1~bpo50+1) depends on missing:
2080 #   - libltdl-dev (>= 2.2.6a-2)
2081 # source---libcanberra (= 0.22-1~bpo50+1): FAILED
2082 #   source---libcanberra (= 0.22-1~bpo50+1) depends on missing:
2083 #   - libltdl-dev
2084 #   - libltdl7-dev (>= 2.2.6)
2085
2086         if (/^\s+/) {
2087             s/^(\s*)$sourceprefix(.*)depends on/$1$2build-depends on/o;
2088             s/^(\s*)$sourceprefix(.*) and (.*) conflict/$1$2 build-conflicts with $3/o;
2089             $explanation .= $_;
2090         } else {
2091             if (/^$sourceprefix(.*) \(.*\): FAILED/o) {
2092                 $result->{$binpkg} = $explanation if $binpkg;
2093                 $explanation = "";
2094                 $binpkg = $1;
2095             } elsif (/^(depwait---.*) \(.*\): FAILED/o) {
2096                 $result->{$binpkg} = $explanation if $binpkg;
2097                 $explanation = "";
2098                 $binpkg = $1;
2099             } else { # else something broken is happening
2100                 #print "ignoring $_\n";
2101                 1;
2102             }
2103         }
2104     }
2105
2106     close $result_cmd;
2107     $result->{$binpkg} = $explanation if $binpkg;
2108     return $result;
2109
2110 }
2111
2112
2113 sub call_edos_depcheck {
2114     return if $simulate_edos;
2115     my $args = shift;
2116     my $srcs = $args->{'srcs'};
2117     my $key;
2118     
2119     return if defined ($distributions{$distribution}{noadw}) && not defined $args->{'depwait'};
2120
2121     # We need to check all of needs-build, as any new upload could make
2122     # something in needs-build have uninstallable deps
2123     # We also check everything in bd-uninstallable, as any new upload could
2124     # make that work again
2125     my (%interesting_packages, %interesting_packages_depwait);
2126     my $db = get_all_source_info();
2127     foreach $key (keys %$db) {
2128         my $pkg = $db->{$key};
2129         if (defined $pkg and isin($pkg->{'state'}, qw/Needs-Build BD-Uninstallable/) and not defined ($distributions{$distribution}{noadw})) {
2130                 $interesting_packages{$key} = undef;
2131         }
2132         if (defined $pkg and isin($pkg->{'state'}, qw/Dep-Wait/) and defined $args->{'depwait'}) {
2133                 $interesting_packages_depwait{$key} = undef;
2134                 # we always check for BD-Uninstallability in depwait - could be that depwait is satisfied but package is uninstallable
2135                 $interesting_packages{$key} = undef unless defined ($distributions{$distribution}{noadw});
2136         }
2137     }
2138     
2139     #print "I would look at these sources with edos-depcheck:\n";
2140     #print join " ", keys %interesting_packages,"\n";
2141     return unless %interesting_packages || %interesting_packages_depwait;
2142
2143     my $tmpfile_pattern = "/tmp/wanna-build-interesting-sources-$distribution.$$-XXXXX";
2144     use File::Temp qw/ tempfile /;
2145     my ($SOURCES, $tmpfile) = tempfile( $tmpfile_pattern, UNLINK => 1 );
2146     for my $key (keys %interesting_packages) {
2147         my $pkg = $db->{$key};
2148         # we print the source files as binary ones (with "source---"-prefixed),
2149         # so we can try if these "binary" packages are installable.
2150         # If such a "binary" package is installable, the corresponding source package is buildable.
2151         print $SOURCES "Package: source---$key\n";
2152         print $SOURCES "Version: $pkg->{'version'}\n";
2153         my $t = &filterarch($srcs->{$key}{'dep'} || $srcs->{$key}{'depends'}, $arch);
2154         my $tt = &filterarch($pkg->{'extra_depends'}, $arch);
2155         $t = $t ? ($tt ? "$t, $tt" : $t) : $tt;
2156         print $SOURCES "Depends: $t\n" if $t;
2157         my $u = &filterarch($srcs->{$key}{'conf'} || $srcs->{$key}{'conflicts'}, $arch);
2158         my $uu = &filterarch($pkg->{'extra_conflicts'}, $arch);
2159         $u = $u ? ($uu ? "$u, $uu" : $u) : $uu;
2160         print $SOURCES "Conflicts: $u\n" if $u;
2161         print $SOURCES "Architecture: all\n";
2162         print $SOURCES "\n";
2163     }
2164     for my $key (keys %interesting_packages_depwait) {
2165         my $pkg = $db->{$key};
2166         # we print the source files as binary ones (with "depwait---"-prefixed),
2167         # so we can try if these "binary" packages are installable.
2168         # If such a "binary" package is installable, the corresponding source package goes out of depwait
2169         print $SOURCES "Package: depwait---$key\n";
2170         print $SOURCES "Version: $pkg->{'version'}\n";
2171         print $SOURCES "Depends: $pkg->{'depends'}\n";
2172         print $SOURCES "Architecture: all\n";
2173         print $SOURCES "\n";
2174     }
2175     close $SOURCES;
2176
2177     my $edosresults = wb_edos_builddebcheck({'arch' => $args->{'arch'}, 'pkgs' => $args->{'pkgs'}, 'src' => $tmpfile});
2178     if (ref($edosresults) eq 'HASH') {
2179         foreach my $key (grep { $_ !~ /^depwait---/ } keys %$edosresults) {
2180                 if (exists $interesting_packages{$key}) {
2181                     $interesting_packages{$key} = $edosresults->{$key};
2182                 } else {
2183                     #print "TODO: edos reported a package we do not care about now\n" if $verbose;
2184                 }
2185         }
2186         foreach my $key (grep { $_ =~ /^depwait---/ } keys %$edosresults) {
2187                 $key =~ /^depwait---(.*)/ and $key = $1;
2188                 if (exists $interesting_packages_depwait{$key}) {
2189                     $interesting_packages_depwait{$key} = $edosresults->{"depwait---".$key};
2190                 } else {
2191                     #print "TODO: edos reported a package we do not care about now\n" if $verbose;
2192                 }
2193         }
2194     } else {
2195         # if $edosresults isn't an hash, then something went wrong and the string is the error message
2196         print "ERROR: Could not run wb-edos-builddebcheck. I am continuing, assuming\n" .
2197              "all packages have installable build-dependencies."
2198     }
2199     
2200     unlink( $tmpfile );
2201
2202     for my $key (keys %interesting_packages) {
2203         next if defined $interesting_packages_depwait{$key};
2204         my $pkg = $db->{$key};
2205         my $change = 
2206             (defined $interesting_packages{$key} and $pkg->{'state'} eq 'Needs-Build') ||
2207             (not defined $interesting_packages{$key} and $pkg->{'state'} eq 'BD-Uninstallable');
2208         my $problemchange = ($interesting_packages{$key}//"") ne ($pkg->{'bd_problem'}//"");
2209         if ($change) {
2210             if (defined $interesting_packages{$key}) {
2211                     change_state( \$pkg, 'BD-Uninstallable' );
2212                     $pkg->{'bd_problem'} = $interesting_packages{$key};
2213             } else {
2214                     change_state( \$pkg, 'Needs-Build' );
2215             }
2216         }
2217         if ($problemchange) {
2218             if (defined $interesting_packages{$key}) {
2219                     $pkg->{'bd_problem'} = $interesting_packages{$key};
2220             }   
2221         }
2222         if ($change) {
2223             log_ta( $pkg, "--merge-all (edos)" ) unless $simulate;
2224             print "edos-builddebchange changed state of ${key}_$pkg->{'version'} ($args->{'arch'}) to $pkg->{'state'}\n" if $verbose || $simulate;
2225         }
2226         if ($change || $problemchange) {
2227             update_source_info($pkg) unless $simulate;
2228         }
2229     }
2230
2231     for my $key (keys %interesting_packages_depwait) {
2232         if ($interesting_packages_depwait{$key}) {
2233             print "dep-wait for $key ($args->{'arch'}) not fullfiled yet\n" if $verbose || $simulate;
2234             next;
2235         }
2236         my $pkg = $db->{$key};
2237             if (defined $interesting_packages{$key}) {
2238                     change_state( \$pkg, 'BD-Uninstallable' );
2239                     $pkg->{'bd_problem'} = $interesting_packages{$key};
2240             } else {
2241                     change_state( \$pkg, 'Needs-Build' );
2242             }
2243         log_ta( $pkg, "edos_depcheck: depwait" ) unless $simulate;
2244         update_source_info($pkg) unless $simulate;
2245         print "edos-builddebchange changed state of ${key}_$pkg->{'version'} ($args->{'arch'}) from dep-wait to $pkg->{'state'}\n" if $verbose || $simulate;
2246     }
2247 }
2248
2249 sub usage {
2250         my $prgname;
2251         ($prgname = $0) =~ s,^.*/,,;
2252         print <<"EOF";
2253 Usage: $prgname <options...> <package_version...>
2254 Options:
2255     -v, --verbose: Verbose execution.
2256     -A arch: Architecture this operation is for.
2257     --take: Take package for building [default operation]
2258     -f, --failed: Record in database that a build failed due to
2259         deficiencies in the package (that aren't fixable without a new
2260         source version).
2261     -u, --uploaded: Record in the database that the packages build
2262         correctly and were uploaded.
2263     -n, --no-build: Record in the database that the packages aren't
2264         desired for this architecture and shouldn't appear in listings even
2265         if they're out of date.
2266     --dep-wait: Record in the database that the packages are waiting
2267         for some source dependencies to become available
2268     --binNMU num: Schedule a re-build of the package with unchanged source, but
2269          a new version number (source-version + "+b<num>")
2270     --give-back: Mark a package as ready to build that is in state Building,
2271          Built or Build-Attempted. To give back a package in state Failed, use
2272          --override. This command will actually put the package in state
2273          BD-Uninstallable, until the installability of its Build-Dependencies
2274          were verified. This happens at each call of --merge-all, usually
2275          every 15 minutes.
2276     --pretend-avail: Pretend that given packages are available now and give
2277         free packages waiting for them
2278     -i SRC_PKG, --info SRC_PKG: Show information for source package
2279     -l STATE, --list=STATE: List all packages in state STATE; can be
2280         combined with -U to restrict to a specific user; STATE can
2281         also be 'all'
2282     -m MESSAGE, --message=MESSAGE: Give reason why package failed or
2283         source dependency list
2284         (used with -f, --dep-wait, and --binNMU)
2285     -o, --override: Override another user's lock on a package, i.e.
2286         take it over; a notice mail will be sent to the other user
2287     -U USER, --user=USER: select user name for which listings should
2288         apply, if not given all users are listed.
2289         if -l is missing, set user name to be entered in db; usually
2290         automatically choosen
2291     --import FILE: Import database from a ASCII file FILE
2292     --export FILE: Export database to a ASCII file FILE
2293
2294 The remaining arguments (depending on operation) usually start with
2295 "name_version", the trailer is ignored. This allows to pass the names
2296 of .dsc files, for which file name completion can be used.
2297 --merge-packages and --merge-quinn take Package/quin--diff file names
2298 on the command line or read stdin. --list needs nothing more on the
2299 command line. --info takes source package names (without version).
2300 EOF
2301         exit 1;
2302 }
2303
2304 sub pkg_version_eq {
2305         my $pkg = shift;
2306         my $version = shift;
2307
2308         return 1
2309                if (defined $pkg->{'binary_nmu_version'}) and 
2310                version_compare(binNMU_version($pkg->{'version'},
2311                         $pkg->{'binary_nmu_version'}),'=', $version);
2312         return version_compare( $pkg->{'version'}, "=", $version );
2313 }
2314
2315 sub table_name {
2316         return '"' . $arch . $schema_suffix . '".packages';
2317 }
2318
2319 sub user_table_name {
2320         return '"' . $arch . $schema_suffix . '".users';
2321 }
2322
2323 sub transactions_table_name {
2324         return '"' . $arch . $schema_suffix . '".transactions';
2325 }
2326
2327 sub pkg_history_table_name {
2328         return '"' . $arch . $schema_suffix . '".pkg_history';
2329 }
2330
2331 sub get_readonly_source_info {
2332         my $name = shift;
2333         # SELECT FLOOR(EXTRACT('epoch' FROM age(localtimestamp, '2010-01-22  23:45')) / 86400) -- change to that?
2334         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"
2335             . ", (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"
2336             . ", (SELECT max(build_time) FROM ".pkg_history_table_name()." WHERE pkg_history.package = packages.package AND pkg_history.distribution = packages.distribution ) AS anytime"
2337             . ", extra_depends, extra_conflicts, build_arch_all"
2338             . " FROM " .  table_name()
2339             . ' WHERE package = ? AND distribution = ?';
2340         my $pkg = $dbh->selectrow_hashref( $q,
2341                 undef, $name, $distribution);
2342         return $pkg;
2343 }
2344
2345 sub get_source_info {
2346         my $name = shift;
2347         return get_readonly_source_info($name) if $simulate;
2348         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 ' . 
2349                 table_name() . ' WHERE package = ? AND distribution = ?' .
2350                 ' FOR UPDATE',
2351                 undef, $name, $distribution);
2352         return $pkg;
2353 }
2354
2355 sub get_all_source_info {
2356         my %options = @_;
2357
2358         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"
2359 #            . ", (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"
2360 #            . ", (SELECT max(build_time) FROM ".pkg_history_table_name()." WHERE pkg_history.package = packages.package AND pkg_history.distribution = packages.distribution ) AS anytime"
2361             . ", successtime.build_time as successtime, anytime.build_time as anytime, extra_depends, extra_conflicts"
2362             . " FROM " .  table_name()
2363                 . " left join ( "
2364                   . "select distinct on (package, distribution) build_time, package, distribution from ".pkg_history_table_name()." where result = 'successful' order by package, distribution, timestamp "
2365                   . " ) as successtime using (package, distribution) "
2366                 . " left join ( "
2367                   . "select distinct on (package, distribution) build_time, package, distribution from ".pkg_history_table_name()." order by package, distribution, timestamp desc"
2368                   . " ) as anytime using (package, distribution) "
2369             . " WHERE TRUE ";
2370         my @args = ();
2371         if ($distribution) {
2372             my @dists = split(/[, ]+/, $distribution);
2373             $q .= ' AND ( distribution = ? '.(' OR distribution = ? ' x $#dists).' )';
2374             foreach my $d ( @dists ) {
2375                 push @args, ($d);
2376             }
2377         }
2378         if ($options{state} && uc($options{state}) ne "ALL") {
2379                 $q .= ' AND upper(state) = ? ';
2380                 push @args, uc($options{state});
2381         }
2382
2383         if ($options{user} && uc($options{state}) ne "NEEDS-BUILD") { # if it's NEEDS-BUILD, we don't look at users
2384                 #this basically means "this user, or no user at all":
2385                 $q .= " AND (builder = ? OR upper(state) = 'NEEDS-BUILD')";
2386                 push @args, $options{user};
2387         }
2388
2389         if ($options{category}) {
2390                 $q .= ' AND failed_category <> ? AND upper(state) = ? ';
2391                 push @args, $options{category};
2392                 push @args, "FAILED";
2393         }
2394
2395         if ($options{list_min_age} && $options{list_min_age} > 0) {
2396                 $q .= ' AND age(state_change) > ? ';
2397                 push @args, $options{list_min_age} . " days";
2398         }
2399
2400         if ($options{list_min_age} && $options{list_min_age} < 0) {
2401                 $q .= ' AND age(state_change) < ? ';
2402                 push @args, -$options{list_min_age} . " days";
2403         }
2404
2405         my $db = $dbh->selectall_hashref($q, 'package', undef, @args);
2406         return $db;
2407 }
2408
2409 sub show_distribution_architectures {
2410         my $q = 'SELECT distribution, spacecat_all(architecture) AS architectures '.
2411                 'FROM distribution_architectures '.
2412                 'GROUP BY distribution';
2413         my $rows = $dbh->selectall_hashref($q, 'distribution');
2414         foreach my $name (keys %$rows) {
2415                 print $name.': '.$rows->{$name}->{'architectures'}."\n";
2416         }
2417 }
2418
2419 sub show_distribution_aliases {
2420         foreach my $alias (keys %distribution_aliases) {
2421                 print $alias.': '.$distribution_aliases{$alias}."\n";
2422         }
2423 }
2424
2425 sub update_source_info {
2426         my $pkg = shift;
2427         $pkg->{'extra_depends'} = $extra_depends if defined $extra_depends;
2428         undef $pkg->{'extra_depends'} unless $pkg->{'extra_depends'};
2429         $pkg->{'extra_conflicts'} = $extra_conflicts if defined $extra_conflicts;
2430         undef $pkg->{'extra_conflicts'} unless $pkg->{'extra_conflicts'};
2431         print Dumper $pkg if $verbose and $simulate;
2432         return if $simulate;
2433
2434         my $pkg2 = get_source_info($pkg->{'package'});
2435         if (! defined $pkg2)
2436         {
2437                 add_source_info($pkg);
2438         }
2439
2440         $dbh->do('UPDATE ' . table_name() . ' SET ' .
2441                         'version = ?, ' .
2442                         'state = ?, ' .
2443                         'section = ?, ' .
2444                         'priority = ?, ' .
2445                         'installed_version = ?, ' .
2446                         'previous_state = ?, ' .
2447                         (($pkg->{'do_state_change'}) ? "state_change = now()," : "").
2448                         'notes = ?, ' .
2449                         'builder = ?, ' .
2450                         'failed = ?, ' .
2451                         'old_failed = ?, ' .
2452                         'binary_nmu_version = ?, ' .
2453                         'binary_nmu_changelog = ?, ' .
2454                         'failed_category = ?, ' .
2455                         'permbuildpri = ?, ' .
2456                         'buildpri = ?, ' .
2457                         'depends = ?, ' .
2458                         'rel = ?, ' .
2459                         'extra_depends = ?, ' .
2460                         'extra_conflicts = ?, ' .
2461                         'bd_problem = ? ' .
2462                         'WHERE package = ? AND distribution = ?',
2463                 undef,
2464                 $pkg->{'version'},
2465                 $pkg->{'state'},
2466                 $pkg->{'section'},
2467                 $pkg->{'priority'},
2468                 $pkg->{'installed_version'},
2469                 $pkg->{'previous_state'},
2470                 $pkg->{'notes'},
2471                 $pkg->{'builder'},
2472                 $pkg->{'failed'},
2473                 $pkg->{'old_failed'},
2474                 $pkg->{'binary_nmu_version'},
2475                 $pkg->{'binary_nmu_changelog'},
2476                 $pkg->{'failed_category'},
2477                 $pkg->{'permbuildpri'},
2478                 $pkg->{'buildpri'},
2479                 $pkg->{'depends'},
2480                 $pkg->{'rel'},
2481                 $pkg->{'extra_depends'},
2482                 $pkg->{'extra_conflicts'},
2483                 $pkg->{'bd_problem'},
2484                 $pkg->{'package'},
2485                 $distribution) or die $dbh->errstr;
2486 }
2487
2488 sub add_source_info {
2489         return if $simulate;
2490         my $pkg = shift;
2491         $dbh->do('INSERT INTO ' . table_name() .
2492                         ' (package, distribution) values (?, ?)',
2493                 undef, $pkg->{'package'}, $distribution) or die $dbh->errstr;
2494 }
2495
2496 sub del_source_info {
2497         return if $simulate;
2498         my $name = shift;
2499         $dbh->do('DELETE FROM ' . table_name() .
2500                         ' WHERE package = ? AND distribution = ?',
2501                 undef, $name, $distribution) or die $dbh->errstr;
2502 }
2503
2504 sub get_user_info {
2505         my $name = shift;
2506         my $user = $dbh->selectrow_hashref('SELECT * FROM ' . 
2507                 user_table_name() . ' WHERE username = ? AND distribution = ?',
2508                 undef, $name, $distribution);
2509         return $user;
2510 }
2511
2512 sub update_user_info {
2513         return if $simulate;
2514         my $user = shift;
2515         $dbh->do('UPDATE ' . user_table_name() .
2516                         ' SET last_seen = now() WHERE username = ?' .
2517                         ' AND distribution = ?',
2518                 undef, $user, $distribution)
2519                 or die $dbh->errstr;
2520 }
2521
2522
2523 sub add_user_info {
2524         return if $simulate;
2525         my $user = shift;
2526         $dbh->do('INSERT INTO ' . user_table_name() .
2527                         ' (username, distribution, last_seen)' .
2528                         ' values (?, ?, now())',
2529                 undef, $user, $distribution)
2530                 or die $dbh->errstr;
2531 }
2532
2533 sub lock_table {
2534         return if $simulate;
2535         $dbh->do('LOCK TABLE ' . table_name() .
2536                 ' IN EXCLUSIVE MODE', undef) or die $dbh->errstr;
2537 }
2538
2539 sub parse_argv {
2540 # parts the array $_[0] and $_[1] and returns the sub-array (modifies the original one)
2541     my @ret = ();
2542     my $args = shift;
2543     my $separator = shift;
2544     while($args->[0] && $args->[0] ne $separator) { 
2545         push @ret, shift @$args;
2546     }
2547     shift @$args if @$args;
2548     return @ret;
2549 }
2550
2551 sub parse_all_v3 {
2552     my $srcs = shift;
2553     my $vars = shift;
2554     my $db = get_all_source_info();
2555     my $binary = $srcs->{'_binary'};
2556
2557     SRCS:
2558     foreach my $name (keys %$srcs) {
2559         next if $name eq '_binary';
2560
2561         # state = installed, out-of-date, uncompiled, not-for-us, auto-not-for-us
2562         my $pkgs = $srcs->{$name};
2563         my $pkg = $db->{$name};
2564
2565         unless ($pkg) {
2566             next SRCS if $pkgs->{'status'} eq 'not-for-us';
2567             my $logstr = sprintf("merge-v3 %s %s_%s (%s, %s):", $vars->{'time'}, $name, $pkgs->{'version'}, $vars->{'arch'}, $vars->{'suite'});
2568
2569             # does at least one binary exist in the database and is more recent - if so, we're probably just outdated, ignore the source package
2570             for my $bin (@{$pkgs->{'binary'}}) {
2571                 if ($binary->{$bin} and vercmp($pkgs->{'version'}, $binary->{$bin}->{'version'}) < 0) {
2572                     print "$logstr skipped because binaries (assumed to be) overwritten\n" if $verbose || $simulate;
2573                     next SRCS;
2574                 }
2575             }
2576             $pkg->{'package'}  = $name;
2577         }
2578         my $logstr = sprintf("merge-v3 %s %s_%s", $vars->{'time'}, $name, $pkgs->{'version'}).
2579             ($pkgs->{'binnmu'} ? ";b".$pkgs->{'binnmu'} : "").
2580             sprintf(" (%s, %s, previous: %s", $vars->{'arch'}, $vars->{'suite'}, $pkg->{'version'}//"").
2581             ($pkg->{'binary_nmu_version'} ? ";b".$pkg->{'binary_nmu_version'} : "").
2582             ", $pkg->{'state'}):";
2583
2584         if (isin($pkgs->{'status'}, qw (installed related)) && $pkgs->{'version'} eq $pkg->{'version'} && $pkgs->{'binnmu'}//0 < int($pkg->{'binary_nmu_version'}//0)) {
2585                 $pkgs->{'status'} = 'out-of-date';
2586         }
2587         if (isin($pkgs->{'status'}, qw (installed related))) {
2588             my $change = 0;
2589             if ($pkg->{'state'} ne 'Installed') {
2590                 change_state( \$pkg, 'Installed');
2591                 delete $pkg->{'depends'};
2592                 delete $pkg->{'extra_depends'};
2593                 delete $pkg->{'extra_conflicts'};
2594                 $change++;
2595             }
2596             my $attrs = { 'version' => 'version', 'installed_version' => 'version', 'binary_nmu_version' => 'binnmu', 'section' => 'section', 'priority' => 'priority' };
2597             foreach my $k (keys %$attrs) {
2598                 if (($pkg->{$k}//"") ne ($pkgs->{$attrs->{$k}}//"")) {
2599                     $pkg->{$k} = $pkgs->{$attrs->{$k}};
2600                     $change++;
2601                 }
2602             }
2603             if (isin($pkgs->{'status'}, qw (related)) and $pkg->{'notes'} ne "related") {
2604                 $pkg->{'notes'} = "related";
2605                 $change++;
2606             }
2607             if ($change) {
2608                 print "$logstr set to installed/".($pkg->{'notes'}//"")."\n" if $verbose || $simulate;
2609                 log_ta( $pkg, "--merge-v3: installed" ) unless $simulate;
2610                 update_source_info($pkg) unless $simulate;
2611             }
2612             next;
2613         }
2614
2615         if ($pkgs->{'status'} eq 'not-for-us') {
2616             next if isin( $pkg->{'state'}, qw(Not-For-Us Installed Failed-Removed));
2617
2618             if (isin( $pkg->{'state'}, qw(Failed Build-Attempted Built))) {
2619                 change_state( \$pkg, "Failed-Removed" );
2620                 log_ta( $pkg, "--merge-v3: Failed-Removed" ) unless $simulate;
2621                 update_source_info($pkg) unless $simulate;
2622                 print "$logstr (virtually) deleted from database\n" if $verbose || $simulate;
2623                 next;
2624             }
2625
2626             print "$logstr should delete (not-for-us according to P-a-s)\n" if $verbose || $simulate || 1; # not implemented yet on purpose
2627             next;
2628         }
2629
2630         if ($pkgs->{'status'} eq 'auto-not-for-us') {
2631             next if isin( $pkg->{'state'}, qw(Not-For-Us Failed Failed-Removed Dep-Wait Dep-Wait-Removed Auto-Not-For-Us));
2632             # if the package is currently current, the status is Installed, not not-for-us
2633
2634             change_state( \$pkg, "Auto-Not-For-Us" );
2635             log_ta( $pkg, "--merge-v3: Auto-Not-For-Us" ) unless $simulate;
2636             update_source_info($pkg) unless $simulate;
2637             print "$logstr set to auto-not-for-us\n" if $verbose || $simulate;
2638             next SRCS;
2639         }
2640
2641         # only uncompiled / out-of-date are left, so check if anything new
2642         if (!(isin($pkgs->{'status'}, qw (uncompiled out-of-date)))) {
2643             print "$logstr package in unknown state: $pkgs->{'status'}\n";
2644             next SRCS;
2645         }
2646         next if $pkgs->{'version'} eq $pkg->{'version'} and $pkgs->{'binnmu'}//0 >= int($pkg->{'binary_nmu_version'}//0);
2647         next if $pkgs->{'version'} eq $pkg->{'version'} and !isin( $pkg->{'state'}, qw(Installed));
2648         next if isin( $pkg->{'state'}, qw(Not-For-Us Failed-Removed));
2649
2650         if (defined( $pkg->{'state'} ) && isin( $pkg->{'state'}, qw(Building Built Build-Attempted))) {
2651             send_mail( $pkg->{'builder'},
2652                 "new version of $name (dist=$distribution)",
2653                 "As far as I'm informed, you're currently building the package $name\n".
2654                 "in version $pkg->{'version'}.\n\n".
2655                 "Now there's a new source version $pkgs->{'version'}. If you haven't finished\n".
2656                 "compiling $name yet, you can stop it to save some work.\n".
2657                 "Just to inform you...\n".
2658                 "(This is an automated message)\n" ) unless $simulate;
2659             print "$logstr new version while building $pkg->{'version'} -- sending mail to builder ($pkg->{'builder'})\n"
2660                                   if $verbose || $simulate;
2661             }
2662         change_state( \$pkg, 'Needs-Build');
2663         $pkg->{'notes'} = $pkgs->{'status'};
2664         $pkg->{'version'} = $pkgs->{'version'};
2665         $pkg->{'section'} = $pkgs->{'section'};
2666         $pkg->{'priority'} = $pkgs->{'priority'};
2667         $pkg->{'dep'} = $pkgs->{'depends'};
2668         $pkg->{'conf'} = $pkgs->{'conflicts'};
2669         delete $pkg->{'builder'};
2670         delete $pkg->{'binary_nmu_version'} unless $pkgs->{'binnmu'};
2671         delete $pkg->{'binary_nmu_changelog'} unless $pkgs->{'binnmu'};
2672         log_ta( $pkg, "--merge-v3: needs-build" ) unless $simulate;
2673         update_source_info($pkg) unless $simulate;
2674         print "$logstr set to needs-builds\n" if $simulate || $verbose;
2675     }
2676
2677     foreach my $name (keys %$db) {
2678         next if $srcs->{$name};
2679         my $pkg = $db->{$name};
2680         my $logstr = "merge-v3 $vars->{'time'} ".$name."_$pkg->{'version'} ($vars->{'arch'}, $vars->{'suite'}, previous: $pkg->{'state'}):";
2681         # package disappeared - delete
2682         change_state( \$pkg, 'deleted' );
2683         log_ta( $pkg, "--merge-v3: deleted" ) unless $simulate;
2684         print "$logstr deleted from database\n" if $verbose || $simulate;
2685         del_source_info($name) unless $simulate;
2686         delete $db->{$name};
2687     }
2688 }