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