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