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