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