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