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