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