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