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