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