]> git.donarmstrong.com Git - wannabuild.git/blob - bin/wanna-build
Perl operator precedence mistake
[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 "/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 GDBM_File;
42 use MLDBM qw(GDBM_File Storable);
43 use WannaBuild;
44
45 our ($verbose, $mail_logs, $list_order, $list_state,
46     $curr_date, $op_mode, $user, $real_user, $distribution,
47     $fail_reason, $opt_override, $import_from, $export_to, $opt_create_db,
48     %db, %otherdb, %otherdb_lock, %prioval, %sectval,
49     $info_all_dists, $arch,
50     $category, %catval, %short_category,
51     $short_date, $list_min_age, $dbbase, @curr_time,
52     $build_priority, %new_vers, $binNMUver, %merge_srcvers, %merge_binsrc,
53     $lock_for_pid, $transactional);
54
55 # global vars
56 $ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin";
57 $verbose = 0;
58 $mail_logs = "";
59 @curr_time = gmtime;
60 $curr_date = strftime("%Y %b %d %H:%M:%S",@curr_time);
61 $short_date = strftime("%m/%d/%y",@curr_time);
62 $| = 1;
63 $lock_for_pid = -1; # -1 means normal procedure
64 $transactional = 0; # 0 means: work on main copy
65
66 # map program invocation names to operation modes
67 my %prognames = ( "uploaded-build"  => "set-uploaded",
68                                   "failed-build"    => "set-failed",
69                                   "no-build"            => "set-not-for-us",
70                                   "give-back-build" => "set-needs-build",
71                                   "dep-wait-build"  => "set-dep-wait",
72                                   "forget-build"        => "forget",
73                                   "merge-quinn"         => "merge-quinn",
74                                   "merge-packages"  => "merge-packages",
75                                   "merge-sources"   => "merge-sources",
76                                   "build-info"          => "info" );
77
78 %short_category = ( u => "uploaded-fixed-pkg",
79                                     f => "fix-expected",
80                                         r => "reminder-sent",
81                                         n => "nmu-offered",
82                                         e => "easy",
83                                         m => "medium",
84                                         h => "hard",
85                                         c => "compiler-error",
86                                         "" => "none" );
87
88 my $progname;
89 ($progname = $0) =~ s,.*/,,;
90 if ($prognames{$progname}) {
91         $op_mode = $prognames{$progname};
92 }
93 elsif ($progname =~ /^list-(.*)$/) {
94         $op_mode = "list";
95         $list_state = ($1 eq "all") ? "" : $1;
96 }
97
98 my %options =
99         (# flags
100          verbose        => { short => "v", flag => \$verbose },
101          override               => { short => "o", flag => \$opt_override },
102          "create-db"    => { flag => \$opt_create_db },
103          "correct-compare" => { flag => \$WannaBuild::opt_correct_version_cmp },
104          # TODO: remove after buildds no longer pass to wanna-build
105          "no-propagation" => { short => "N" },
106          "no-down-propagation" => { short => "D" },
107          # normal actions
108          take                   => { mode => "set-building" },
109          failed                 => { short => "f", mode => "set-failed" },
110          uploaded               => { short => "u", mode => "set-uploaded" },
111          "no-build"             => { short => "n", mode => "set-not-for-us" },
112          built                  => { mode => "set-built" },
113          attempted              => { mode => "set-attempted" },
114          "give-back"            => { mode => "set-needs-build" },
115          "dep-wait"             => { mode => "set-dep-wait" },
116          forget                 => { mode => "forget" },
117          'forget-user' => { mode => 'forget-user' },
118          "merge-quinn"  => { mode => "merge-quinn" },
119          "merge-partial-quinn" => { mode => "merge-partial-quinn" },
120          "merge-packages" => { mode => "merge-packages" },
121          "merge-sources" => { mode => "merge-sources" },
122          "pretend-avail" => { short => "p", mode => "pretend-avail" },
123          "merge-all"     => { mode => "merge-all" },
124          info                   => { short => "i", mode => "info" },
125          'binNMU' => { mode => 'set-binary-nmu', arg => \$binNMUver, 
126                              code => sub { die "Invalid binNMU version: $binNMUver\n"
127                                 if $binNMUver !~ /^([\d]*)$/ and $1 >= 0; } },
128          'perm-build-priority'    => { mode => "set-permanent-build-priority", arg => \$build_priority,
129                               code => sub { die "Invalid build priority: $build_priority\n"
130                                 if $build_priority !~ /^-?[\d]+$/; } },
131          'build-priority'    => { mode => "set-build-priority", arg => \$build_priority,
132                               code => sub { die "Invalid build priority: $build_priority\n"
133                                 if $build_priority !~ /^-?[\d]+$/; } },
134          list                   =>
135          { short => "l", mode => "list", arg => \$list_state,
136            code => sub {
137                    die "Unknown state to list: $list_state\n"
138                            if !isin( $list_state, qw(needs-build building uploaded
139                                                  built build-attempted failed installed dep-wait
140                                                  not-for-us all failed-removed
141                                                  install-wait reupload-wait));} },
142          # options with args
143          dist           =>
144          { short => "d", arg => \$distribution,
145            code => sub {
146                    if ($distribution eq "a" || $distribution eq "all") {
147                            $info_all_dists = 1;
148                            $distribution = "";
149                    }
150                    else {
151                            $distribution = "oldstable"   if $distribution eq "o";
152                            $distribution = "stable"   if $distribution eq "s";
153                            $distribution = "testing"  if $distribution eq "t";
154                            $distribution = "unstable" if $distribution eq "u";
155                    }
156            } },
157          order          =>
158          { short => "O", arg => \$list_order,
159            code => sub {
160                    die "Bad ordering character\n"
161                            if $list_order !~ /^[PSpsncb]+$/;
162            } },
163          message        => { short => "m", arg => \$fail_reason },
164          database       => { short => "b", arg => \$conf::dbbase },
165          arch           => { short => "A", arg => \$arch },
166          user           => { short => "U", arg => \$user },
167          category               => { short => "c", arg => \$category,
168                                                  code => sub {
169                                                          $category = $short_category{$category}
170                                                                  if exists $short_category{$category};
171                                                          die "Unknown category: $category\n"
172                                                                  if !isin( $category, values %short_category );
173                                                  } },
174          "min-age"      => { short => "a", arg => \$list_min_age,
175                                                  code => sub {
176                                                          die "Argument of --min-age must be a non-zero number\n"
177                                                                  if $list_min_age == 0;
178                                                          $list_min_age *= 24*60*60;
179                                                  } },
180          "max-age"      => { arg => \$list_min_age,
181                                                  code => sub {
182                                                          die "Argument of --max-age must be a non-zero number\n"
183                                                                  if $list_min_age == 0;
184                                                          $list_min_age *= -24*60*60;
185                                                  } },
186          # special actions
187          import         => { arg => \$import_from, mode => "import" },
188          export         => { arg => \$export_to, mode => "export" },
189          "lock-for"     => { arg => \$lock_for_pid, mode => "lock-for" },
190          "unlock-for"   => { arg => \$lock_for_pid, mode => "unlock-for" },
191          "act-on-behalf-of" => { arg => \$lock_for_pid },
192          "start-transaction" => { mode => "start-transaction" },
193          "commit-transaction" => { mode => "commit-transaction" },
194          "transactional" => { flag => \$transactional },
195          "manual-edit"  => { mode => "manual-edit" },
196          "create-maintenance-lock" => { mode => "maintlock-create" },
197          "remove-maintenance-lock" => { mode => "maintlock-remove" },
198          "clean-db" => { mode => "clean-db" },
199          );
200
201 while( @ARGV && $ARGV[0] =~ /^-/ ) {
202         $_ = shift @ARGV;
203         last if $_ eq "--";
204         my($opt, $optname, $arg);
205         if (/^--([^=]+)(=|$)/) {
206                 $optname = $1;
207                 $opt = $options{$optname};
208                 $arg = $1 if /^--\Q$optname\E=((.|\n)*)$/;
209         }
210         else {
211                 $optname = substr( $_, 1, 1 );
212                 $opt = (grep { defined($_->{short}) ? $_->{short} eq $optname : 0} values %options)[0];
213                 $arg = $1 if /^-$optname(.+)$/;
214         }
215         if (!$opt) {
216                 warn "Unknown option: --$1\n";
217                 usage();
218         }
219         if ($opt->{arg}) {
220                 if (!defined $arg) {
221                         die "$optname option missing argument\n" if !@ARGV;
222                         $arg = shift @ARGV;
223                 }
224                 ${$opt->{arg}} = $arg;
225         }
226         elsif (defined $arg) {
227                 die "Option $optname takes no argument\n";
228         }
229         
230         if ($opt->{mode}) {
231                 die "Conflicting operation modes\n" if $op_mode;
232                 $op_mode = $opt->{mode};
233         }
234         if ($opt->{flag}) {
235                 ${$opt->{flag}}++;
236         }
237         if ($opt->{code}) {
238                 &{$opt->{code}};
239         }
240 }
241
242 $op_mode = $category ? "set-failed" : "set-building"
243         if !$op_mode; # default operation
244 $list_order = $list_state eq "failed" ? 'fPcpsn' : 'PScpsn'
245         if !$list_order and $list_state;
246 $distribution ||= "unstable";
247 die "Bad distribution '$distribution'\n"
248         if !isin($distribution, keys %conf::distributions);
249
250 if ($verbose) {
251         my $version = '$Revision: db181a534e9d $ $Date: 2008/03/26 06:20:22 $ $Author: rmurray $';
252         $version =~ s/(^\$| \$ .*$)//g;
253         print "wanna-build $version for $distribution on $conf::dbbase\n";
254 }
255
256 if (!@ARGV && !isin( $op_mode, qw(list merge-quinn merge-partial-quinn import export
257                                   merge-packages manual-edit maintlock-create lock-for unlock-for
258                                   start-transaction commit-transaction
259                                   merge-sources maintlock-remove clean-db))) {
260         warn "No packages given.\n";
261         usage();
262 }
263
264 $real_user = (getpwuid($<))[0];
265 die "Can't determine your user name\n"
266         if $op_mode ne "list" && !$user &&
267            !($user = $real_user);
268
269 if (!$fail_reason) {
270         if ($op_mode eq "set-failed" && !$category) {
271                 print "Enter reason for failing (end with '.' alone on ".
272                       "its line):\n";
273                 my $line;
274                 while(!eof(STDIN)) {
275                         $line = <STDIN>;
276                         last if $line eq ".\n";
277                         $fail_reason .= $line;
278                 }
279                 chomp( $fail_reason );
280         } elsif ($op_mode eq "set-dep-wait") {
281                 print "Enter dependencies (one line):\n";
282                 my $line;
283                 while( !$line && !eof(STDIN) ) {
284                         chomp( $line = <STDIN> );
285                 }
286                 die "No dependencies given\n" if !$line;
287                 $fail_reason = $line;
288         } elsif ($op_mode eq "set-binary-nmu" and $binNMUver > 0) {
289                 print "Enter changelog entry (one line):\n";
290                 my $line;
291                 while( !$line && !eof(STDIN) ) {
292                         chomp( $line = <STDIN> );
293                 }
294                 die "No changelog entry given\n" if !$line;
295                 $fail_reason = $line;
296         }
297 }
298 if ($op_mode eq "maintlock-create") {
299         create_maintlock();
300         exit 0;
301 }
302 if ($op_mode eq "maintlock-remove") {
303         remove_maintlock();
304         exit 0;
305 }
306 waitfor_maintlock() if $op_mode !~ /^(?:merge-|clean-db$)/;
307
308 if (!-f db_filename( $distribution ) && !$opt_create_db) {
309         if ($transactional) {
310                 die "No running transaction for $distribution\n";
311         } else {
312                 die "Database for $distribution doesn't exist\n";
313         }
314 }
315
316 # Locking for another process means that a longer running process (most likely
317 # wb) wants to do several steps at once, and manages the locks.
318 if ($op_mode eq "lock-for") {
319         lock_db( $distribution );
320         exit 0;
321 }
322 if ($op_mode eq "unlock-for") {
323         unlock_db( $distribution );
324         exit 0;
325 }
326
327 lock_db( $distribution );
328
329 if ($op_mode eq "start-transaction") {
330         copy ( db_filename_master( $distribution ), db_filename_transaction( $distribution ))
331                 or die "Copy failed: $!";
332         open LOG, ">", db_transactlog_transaction( $distribution )
333                 or die "Could not create logfile for transaction: $!";
334         close LOG;
335         exit 0;
336 }
337
338 if ($op_mode eq "commit-transaction") {
339         # we need to copy here to preserve the owner and group of the file
340         copy ( db_filename_transaction( $distribution ), db_filename_master( $distribution ))
341                 or die "Copy failed: $!";
342         unlink db_filename_transaction( $distribution );
343         open TLOG, "<", db_transactlog_transaction( $distribution )
344                 or die "Could not open logfile from transaction: $!";
345         open LOG, ">>", db_transactlog_master( $distribution )
346                 or die "Could not open logfile: $!";
347         while (<TLOG>) { print LOG $_ };
348         close TLOG;
349         close LOG;
350         unlink db_transactlog_transaction( $distribution );
351         exit 0;
352 }
353
354 END {
355         untie %db;
356         if ($lock_for_pid == -1) {
357                 unlock_db( $distribution );
358         }
359         foreach (keys %conf::distributions) {
360                 untie %{$otherdb{$_}} if tied(%{$otherdb{$_}});
361                 unlock_db( $_ ) if $otherdb_lock{$_};
362         }
363 }
364
365 tie %db, 'MLDBM', db_filename( $distribution ), GDBM_WRCREAT, 0664
366         or die "FATAL: Cannot open database\n";
367
368 process();
369
370 if ($mail_logs && $conf::log_mail) {
371         send_mail( $conf::log_mail,
372                            "wanna-build $distribution state changes $curr_date",
373                            "State changes at $curr_date for distribution ".
374                            "$distribution:\n\n$mail_logs\n" );
375 }
376
377 exit 0;
378
379
380 sub process {
381
382         SWITCH: foreach ($op_mode) {
383                 /^set-(.+)/ && do {
384                         add_packages( $1, @ARGV );
385                         last SWITCH;
386                 };
387                 /^list/ && do {
388                         list_packages( $list_state );
389                         last SWITCH;
390                 };
391                 /^info/ && do {
392                         info_packages( @ARGV );
393                         last SWITCH;
394                 };
395                 /^forget-user/ && do {
396                         die "This operation is restricted to admin users\n"
397                                 if (defined @conf::admin_users and
398                                     !isin( $real_user, @conf::admin_users));
399                         forget_users( @ARGV );
400                         last SWITCH;
401                 };
402                 /^forget/ && do {
403                         forget_packages( @ARGV );
404                         last SWITCH;
405                 };
406                 /^merge-partial-quinn/ && do {
407                         die "This operation is restricted to admin users\n"
408                                 if (defined @conf::admin_users and
409                                     !isin( $real_user, @conf::admin_users));
410                         parse_quinn_diff(1);
411                         last SWITCH;
412                 };
413                 /^merge-quinn/ && do {
414                         die "This operation is restricted to admin users\n"
415                                 if (defined @conf::admin_users and
416                                     !isin( $real_user, @conf::admin_users));
417                         parse_quinn_diff(0);
418                         last SWITCH;
419                 };
420                 /^merge-packages/ && do {
421                         die "This operation is restricted to admin users\n"
422                                 if (defined @conf::admin_users and
423                                     !isin( $real_user, @conf::admin_users));
424                         parse_packages();
425                         last SWITCH;
426                 };
427                 /^merge-sources/ && do {
428                         die "This operation is restricted to admin users\n"
429                                 if (defined @conf::admin_users and
430                                     !isin( $real_user, @conf::admin_users));
431                         parse_sources(0);
432                         last SWITCH;
433                 };
434                 /^pretend-avail/ && do {
435                         pretend_avail( @ARGV );
436                         last SWITCH;
437                 };
438                 /^merge-all/ && do {
439                         die "This operation is restricted to admin users\n"
440                                 if (defined @conf::admin_users and
441                                     !isin( $real_user, @conf::admin_users));
442                         my @ARGS = @ARGV;
443                         @ARGV = ( $ARGS[0] );
444                         my $pkgs = parse_packages();
445                         @ARGV = ( $ARGS[1] );
446                         parse_quinn_diff(0);
447                         @ARGV = ( $ARGS[2] );
448                         my $build_deps = parse_sources(1);
449                         call_edos_depcheck( $ARGS[0], $ARGS[2] );
450                         clean_db();
451                         last SWITCH;
452                 };
453                 /^import/ && do {
454                         die "This operation is restricted to admin users\n"
455                                 if (defined @conf::admin_users and
456                                     !isin( $real_user, @conf::admin_users));
457                         %db = (); # clear all current contents
458                         read_db( $import_from );
459                         last SWITCH;
460                 };
461                 /^export/ && do {
462                         write_db( $export_to );
463                         last SWITCH;
464                 };
465                 /^manual-edit/ && do {
466                         die "This operation is restricted to admin users\n"
467                                 if (defined @conf::admin_users and
468                                     !isin( $real_user, @conf::admin_users));
469                         my $tmpfile_pattern = "/tmp/wanna-build-$distribution.$$-";
470                         my ($tmpfile, $i);
471                         for( $i = 0;; ++$i ) {
472                                 $tmpfile = $tmpfile_pattern . $i;
473                                 last if ! -e $tmpfile;
474                         }
475                         write_db( $tmpfile );
476                         my $editor = $ENV{'VISUAL'} ||
477                                                  "/usr/bin/sensible-editor";
478                         system "$editor $tmpfile";
479                         %db = (); # clear all current contents
480                         read_db( $tmpfile );
481                         unlink( $tmpfile );
482                         last SWITCH;
483                 };
484                 /^clean-db/ && do {
485                         die "This operation is restricted to admin users\n"
486                                 if (defined @conf::admin_users and
487                                     !isin( $real_user, @conf::admin_users));
488                         clean_db();
489                         last SWITCH;
490                 };
491
492                 die "Unexpected operation mode $op_mode\n";
493         }
494         if (not -t and $user =~ /-/) {
495                 my $userinfo = $db{'_userinfo'};
496                 $userinfo = {} if (!defined($userinfo));
497
498                 my $ui = $userinfo->{$user};
499                 $ui = {} if (!defined($ui));
500
501                 $ui->{'Last-Seen'} = $curr_date;
502                 $ui->{'User'} = $user;
503
504                 $userinfo->{$user} = $ui;
505                 $db{'_userinfo'} = $userinfo;
506         }
507 }
508
509 sub add_packages {
510         my $newstate = shift;
511         my( $package, $name, $version, $ok, $reason );
512         
513         foreach $package (@_) {
514                 $package =~ s,^.*/,,; # strip path
515                 $package =~ s/\.(dsc|diff\.gz|tar\.gz|deb)$//; # strip extension
516                 $package =~ s/_[a-zA-Z\d-]+\.changes$//; # strip extension
517                 if ($package =~ /^([\w\d.+-]+)_([\w\d:.+~-]+)/) {
518                         ($name,$version) = ($1,$2);
519                 }
520                 else {
521                         warn "$package: can't extract package name and version ".
522                                  "(bad format)\n";
523                         next;
524                 }
525
526                 if ($op_mode eq "set-building") {
527                         add_one_building( $name, $version );
528                 }
529                 elsif ($op_mode eq "set-built") {
530                         add_one_built( $name, $version );
531                 }
532                 elsif ($op_mode eq "set-attempted") {
533                         add_one_attempted( $name, $version );
534                 }
535                 elsif ($op_mode eq "set-uploaded") {
536                         add_one_uploaded( $name, $version );
537                 }
538                 elsif ($op_mode eq "set-failed") {
539                         add_one_failed( $name, $version );
540                 }
541                 elsif ($op_mode eq "set-not-for-us") {
542                         add_one_notforus( $name, $version );
543                 }
544                 elsif ($op_mode eq "set-needs-build") {
545                         add_one_needsbuild( $name, $version );
546                 }
547                 elsif ($op_mode eq "set-dep-wait") {
548                         add_one_depwait( $name, $version );
549                 }
550                 elsif ($op_mode eq "set-build-priority") {
551                         set_one_buildpri( $name, $version, 'BuildPri' );
552                 }
553                 elsif ($op_mode eq "set-permanent-build-priority") {
554                         set_one_buildpri( $name, $version, 'PermBuildPri' );
555                 }
556                 elsif ($op_mode eq "set-binary-nmu") {
557                         set_one_binnmu( $name, $version );
558                 }
559         }
560 }
561
562 sub add_one_building {
563         my $name = shift;
564         my $version = shift;
565         my( $ok, $reason );
566
567         $ok = 1;
568         my $pkg = $db{$name};
569         if (defined($pkg)) {
570                 if ($pkg->{'State'} eq "Not-For-Us") {
571                         $ok = 0;
572                         $reason = "not suitable for this architecture";
573                 }
574                 elsif ($pkg->{'State'} =~ /^Dep-Wait/) {
575                         $ok = 0;
576                         $reason = "not all source dependencies available yet";
577                 }
578                 elsif ($pkg->{'State'} =~ /^BD-Uninstallable/) {
579                         $ok = 0;
580                         $reason = "source dependencies are not installable";
581                 }
582                 elsif ($pkg->{'State'} eq "Uploaded" &&
583                            (version_lesseq($version, $pkg->{'Version'}))) {
584                         $ok = 0;
585                         $reason = "already uploaded by $pkg->{'Builder'}";
586                         $reason .= " (in newer version $pkg->{'Version'})"
587                                 if !version_eq($pkg, $version);
588                 }
589                 elsif ($pkg->{'State'} eq "Installed" &&
590                            version_less($version,$pkg->{'Version'})) {
591                         if ($opt_override) {
592                                 print "$name: Warning: newer version $pkg->{'Version'} ".
593                                           "already installed, but overridden.\n";
594                         }
595                         else {
596                                 $ok = 0;
597                                 $reason = "newer version $pkg->{'Version'} already in ".
598                                                   "archive; doesn't need rebuilding";
599                                 print "$name: Note: If the following is due to an epoch ",
600                                           " change, use --override\n";
601                         }
602                 }
603                 elsif ($pkg->{'State'} eq "Installed" &&
604                            pkg_version_eq($pkg,$version)) {
605                         $ok = 0;
606                         $reason = "is up-to-date in the archive; doesn't need rebuilding";
607                 }
608                 elsif ($pkg->{'State'} eq "Needs-Build" &&
609                            version_less($version,$pkg->{'Version'})) {
610                         if ($opt_override) {
611                                 print "$name: Warning: newer version $pkg->{'Version'} ".
612                                           "needs building, but overridden.";
613                         }
614                         else {
615                                 $ok = 0;
616                                 $reason = "newer version $pkg->{'Version'} needs building, ".
617                                                   "not $version";
618                         }
619                 }
620                 elsif (isin($pkg->{'State'},qw(Building Built Build-Attempted))) {
621                         if (version_less($pkg->{'Version'},$version)) {
622                                 print "$name: Warning: Older version $pkg->{'Version'} ",
623                                       "is being built by $pkg->{'Builder'}\n";
624                                 if ($pkg->{'Builder'} ne $user) {
625                                         send_mail( $pkg->{'Builder'},
626                                                            "package takeover in newer version",
627                                                            "You are building package '$name' in ".
628                                                            "version $version\n".
629                                                            "(as far as I'm informed).\n".
630                                                            "$user now has taken the newer ".
631                                                            "version $version for building.".
632                                                            "You can abort the build if you like.\n" );
633                                 }
634                         }
635                         else {
636                                 if ($opt_override) {
637                                         print "User $pkg->{'Builder'} had already ",
638                                               "taken the following package,\n",
639                                                   "but overriding this as you request:\n";
640                                         send_mail( $pkg->{'Builder'}, "package takeover",
641                                                            "The package '$name' (version $version) that ".
642                                                            "was locked by you\n".
643                                                            "has been taken over by $user\n" );
644                                 }
645                                 elsif ($pkg->{'Builder'} eq $user) {
646                                         print "$name: Note: already taken by you.\n";
647                                         print "$name: ok\n" if $verbose;
648                                         return;
649                                 }
650                                 else {
651                                         $ok = 0;
652                                         $reason = "already taken by $pkg->{'Builder'}";
653                                         $reason .= " (in newer version $pkg->{'Version'})"
654                                                 if !version_eq($pkg->{'Version'}, $version);
655                                 }
656                         }
657                 }
658                 elsif ($pkg->{'State'} =~ /^Failed/ &&
659                            pkg_version_eq($pkg, $version)) {
660                         if ($opt_override) {
661                                 print "The following package previously failed ",
662                                           "(by $pkg->{'Builder'})\n",
663                                           "but overriding this as you request:\n";
664                                 send_mail( $pkg->{'Builder'}, "failed package takeover",
665                                                    "The package '$name' (version $version) that ".
666                                                    "is locked by you\n".
667                                                    "and has failed previously has been taken over ".
668                                                    "by $user\n" )
669                                         if $pkg->{'Builder'} ne $user;
670                         }
671                         else {
672                                 $ok = 0;
673                                 $reason = "build of $version failed previously:\n    ";
674                                 $reason .= join( "\n    ", split( "\n", $pkg->{'Failed'} ));
675                                 $reason .= "\nalso the package doesn't need builing"
676                                         if $pkg->{'State'} eq 'Failed-Removed';
677                         }
678                 }
679         }
680         if ($ok) {
681                 my $ok = 'ok';
682                 if ($pkg->{'Binary-NMU-Version'}) {
683                         print "$name: Warning: needs binary NMU $pkg->{'Binary-NMU-Version'}\n" .
684                               "$pkg->{'Binary-NMU-Changelog'}\n";
685                         $ok = 'aok';
686                 } else {
687                         print "$name: Warning: Previous version failed!\n"
688                                 if $pkg->{'Previous-State'} =~ /^Failed/ ||
689                                    $pkg->{'State'} =~ /^Failed/;
690                 }
691                 change_state( \$pkg, 'Building' );
692                 $pkg->{'Package'} = $name;
693                 $pkg->{'Version'} = $version;
694                 $pkg->{'Builder'} = $user;
695                 log_ta( $pkg, "--take" );
696                 $db{$name} = $pkg;
697                 print "$name: $ok\n" if $verbose;
698         }
699         else {
700                 print "$name: NOT OK!\n  $reason\n";
701         }
702 }
703
704 sub add_one_attempted {
705         my $name = shift;
706         my $version = shift;
707         my $pkg = $db{$name};
708
709         if (!defined($pkg)) {
710                 print "$name: not registered yet.\n";
711                 return;
712         }
713
714         if ($pkg->{'State'} ne "Building" ) {
715                 print "$name: not taken for building (state is $pkg->{'State'}). ",
716                           "Skipping.\n";
717                 return;
718         }
719         if ($pkg->{'Builder'} ne $user) {
720                 print "$name: not taken by you, but by $pkg->{'Builder'}. Skipping.\n";
721                 return;
722         }
723         elsif ( !pkg_version_eq($pkg, $version) ) {
724                 print "$name: version mismatch ".
725                           "$(pkg->{'Version'} ".
726                           "by $pkg->{'Builder'})\n";
727                 return;
728         }
729
730         change_state( \$pkg, 'Build-Attempted' );
731         log_ta( $pkg, "--attempted" );
732         $db{$name} = $pkg;
733         print "$name: registered as uploaded\n" if $verbose;
734 }
735
736 sub add_one_built {
737         my $name = shift;
738         my $version = shift;
739         my $pkg = $db{$name};
740
741         if (!defined($pkg)) {
742                 print "$name: not registered yet.\n";
743                 return;
744         }
745
746         if ($pkg->{'State'} ne "Building" ) {
747                 print "$name: not taken for building (state is $pkg->{'State'}). ",
748                           "Skipping.\n";
749                 return;
750         }
751         if ($pkg->{'Builder'} ne $user) {
752                 print "$name: not taken by you, but by $pkg->{'Builder'}. Skipping.\n";
753                 return;
754         }
755         elsif ( !pkg_version_eq($pkg, $version) ) {
756                 print "$name: version mismatch ".
757                           "$(pkg->{'Version'} ".
758                           "by $pkg->{'Builder'})\n";
759                 return;
760         }
761         change_state( \$pkg, 'Built' );
762         log_ta( $pkg, "--built" );
763         $db{$name} = $pkg;
764         print "$name: registered as built\n" if $verbose;
765 }
766
767 sub add_one_uploaded {
768         my $name = shift;
769         my $version = shift;
770         my $pkg = $db{$name};
771
772         if (!defined($pkg)) {
773                 print "$name: not registered yet.\n";
774                 return;
775         }
776
777         if ($pkg->{'State'} eq "Uploaded" &&
778                 pkg_version_eq($pkg,$version)) {
779                 print "$name: already uploaded\n";
780                 return;
781         }
782         if (!isin( $pkg->{'State'}, qw(Building Built Build-Attempted))) {
783                 print "$name: not taken for building (state is $pkg->{'State'}). ",
784                           "Skipping.\n";
785                 return;
786         }
787         if ($pkg->{'Builder'} ne $user) {
788                 print "$name: not taken by you, but by $pkg->{'Builder'}. Skipping.\n";
789                 return;
790         }
791         # strip epoch -- buildd-uploader used to go based on the filename.
792         # (to remove at some point)
793         my $pkgver;
794         ($pkgver = $pkg->{'Version'}) =~ s/^\d+://;
795         $version =~ s/^\d+://; # for command line use
796         if ($pkg->{'Binary-NMU-Version'} ) {
797                 my $nmuver = binNMU_version($pkgver, $pkg->{'Binary-NMU-Version'});
798                 if (!version_eq( $nmuver, $version )) {
799                         print "$name: version mismatch ($nmuver registered). ",
800                                   "Skipping.\n";
801                         return;
802                 }
803         } elsif (!version_eq($pkgver, $version)) {
804                 print "$name: version mismatch ($pkg->{'Version'} registered). ",
805                           "Skipping.\n";
806                 return;
807         }
808
809         change_state( \$pkg, 'Uploaded' );
810         log_ta( $pkg, "--uploaded" );
811         $db{$name} = $pkg;
812         print "$name: registered as uploaded\n" if $verbose;
813 }
814
815 sub add_one_failed {
816         my $name = shift;
817         my $version = shift;
818         my ($state, $cat);
819         my $pkg = $db{$name};
820
821         if (!defined($pkg)) {
822                 print "$name: not registered yet.\n";
823                 return;
824         }
825         $state = $pkg->{'State'};
826
827         if ($state eq "Not-For-Us") {
828                 print "$name: not suitable for this architecture anyway. Skipping.\n";
829                 return;
830         }
831         elsif ($state eq "Failed-Removed") {
832                 print "$name: failed previously and doesn't need building. Skipping.\n";
833                 return;
834         }
835         elsif ($state eq "Installed") {
836                 print "$name: Is already installed in archive. Skipping.\n";
837                 return;
838         }
839         elsif ($pkg->{'Builder'} &&
840                    (($user ne $pkg->{'Builder'}) &&
841                     !($pkg->{'Builder'} =~ /^(\w+)-\w+/ && $1 eq $user))) {
842                 print "$name: not taken by you, but by ".
843                           "$pkg->{'Builder'}. Skipping.\n";
844                 return;
845         }
846         elsif ( !pkg_version_eq($pkg, $version) ) {
847                 print "$name: version mismatch ".
848                           "$(pkg->{'Version'} ".
849                           "by $pkg->{'Builder'})\n";
850                 return;
851         }
852
853         $cat = $category;
854         if (!$cat && $fail_reason =~ /^\[([^\]]+)\]/) {
855                 $cat = $1;
856                 $cat = $short_category{$cat} if exists $short_category{$cat};
857                 if (!isin( $cat, values %short_category )) {
858                         print "$name: Warning: unknown category $cat; discarded\n";
859                         $cat = "";
860                 }
861                 $fail_reason =~ s/^\[[^\]]+\][ \t]*\n*//;
862         }
863
864         if ($state eq "Needs-Build") {
865                 print "$name: Warning: not registered for building previously, ".
866                           "but processing anyway.\n";
867         }
868         elsif ($state eq "Uploaded") {
869                 print "$name: Warning: marked as uploaded previously, ".
870                           "but processing anyway.\n";
871         }
872         elsif ($state eq "Dep-Wait") {
873                 print "$name: Warning: marked as waiting for dependencies, ".
874                           "but processing anyway.\n";
875         }
876         elsif ($state eq "BD-Uninstallable") {
877                 print "$name: Warning: marked as having uninstallable build-dependencies, ".
878                           "but processing anyway.\n";
879         }
880         elsif ($state eq "Failed") {
881                 print "$name: already registered as failed; will append new message\n"
882                         if $fail_reason;
883                 print "$name: already registered as failed; changing category\n"
884                         if $cat;
885         }
886
887         if (($cat eq "reminder-sent" || $cat eq "nmu-offered") &&
888                 exists $pkg->{'Failed-Category'} &&
889                 $pkg->{'Failed-Category'} ne $cat) {
890                 (my $action = $cat) =~ s/-/ /;
891                 $fail_reason .= "\n$short_date: $action";
892         }
893
894         change_state( \$pkg, 'Failed' );
895         $pkg->{'Builder'} = $user;
896         $pkg->{'Failed'} .= "\n" if $pkg->{'Failed'};
897         $pkg->{'Failed'} .= $fail_reason;
898         $pkg->{'Failed-Category'} = $cat if $cat;
899         if (defined $pkg->{'PermBuildPri'}) {
900                 $pkg->{'BuildPri'} = $pkg->{'PermBuildPri'};
901         } else {
902                 delete $pkg->{'BuildPri'};
903         }
904         log_ta( $pkg, "--failed" );
905         $db{$name} = $pkg;
906         print "$name: registered as failed\n" if $verbose;
907 }
908
909 sub add_one_notforus {
910         my $name = shift;
911         my $version = shift;
912         my $pkg = $db{$name};
913
914         if ($pkg->{'State'} eq 'Not-For-Us') {
915                 # reset Not-For-Us state in case it's called twice; this is
916                 # the only way to get a package out of this state...
917                 # There is no really good state in which such packages should
918                 # be put :-( So use Failed for now.
919                 change_state( \$pkg, 'Failed' );
920                 $pkg->{'Package'} = $name;
921                 $pkg->{'Failed'} = "Was Not-For-Us previously";
922                 delete $pkg->{'Builder'};
923                 delete $pkg->{'Depends'};
924                 log_ta( $pkg, "--no-build(rev)" );
925                 print "$name: now not unsuitable anymore\n";
926
927                 send_mail( $conf::notforus_maint,
928                                    "$name moved out of Not-For-Us state",
929                                    "The package '$name' has been moved out of the Not-For-Us ".
930                                    "state by $user.\n".
931                                    "It should probably also be removed from ".
932                                    "Packages-arch-specific or\n".
933                                    "the action was wrong.\n" )
934                         if $conf::notforus_maint;
935         }
936         else {
937                 change_state( \$pkg, 'Not-For-Us' );
938                 $pkg->{'Package'} = $name;
939                 delete $pkg->{'Builder'};
940                 delete $pkg->{'Depends'};
941                 delete $pkg->{'BuildPri'};
942                 delete $pkg->{'Binary-NMU-Version'};
943                 delete $pkg->{'Binary-NMU-Changelog'};
944                 log_ta( $pkg, "--no-build" );
945                 print "$name: registered as unsuitable\n" if $verbose;
946
947                 send_mail( $conf::notforus_maint,
948                                    "$name set to Not-For-Us",
949                                    "The package '$name' has been set to state Not-For-Us ".
950                                    "by $user.\n".
951                                    "It should probably also be added to ".
952                                    "Packages-arch-specific or\n".
953                                    "the Not-For-Us state is wrong.\n" )
954                         if $conf::notforus_maint;
955         }
956         $db{$name} = $pkg;
957 }
958
959 sub add_one_needsbuild {
960         my $name = shift;
961         my $version = shift;
962         my $state;
963         my $pkg = $db{$name};
964
965         if (!defined($pkg)) {
966                 print "$name: not registered; can't give back.\n";
967                 return;
968         }
969         $state = $pkg->{'State'};
970
971         if ($state eq "Dep-Wait") {
972                 if ($opt_override) {
973                         print "$name: Forcing source dependency list to be cleared\n";
974                 }
975                 else {
976                         print "$name: waiting for source dependencies. Skipping\n",
977                                   "  (use --override to clear dependency list and ",
978                                   "give back anyway)\n";
979                         return;
980                 }
981         }
982         if ($state eq "BD-Uninstallable") {
983                 if ($opt_override) {
984                         print "$name: Forcing uninstallability mark to be removed\n";
985                 }
986                 else {
987                         print "$name: has uninstallable build-dependencies. Skipping\n",
988                                   "  (use --override to clear dependency list and ",
989                                   "give back anyway)\n";
990                         return;
991                 }
992         }
993         elsif (!isin( $state, qw(Building Built Build-Attempted))) {
994                 print "$name: not taken for building (state is $state).";
995                 if ($opt_override) {
996                         print "\n$name: Forcing give-back\n";
997                 }
998                 else {
999                         print " Skipping.\n";
1000                         return;
1001                 }
1002         }
1003         if (defined ($pkg->{'Builder'}) && $user ne $pkg->{'Builder'} &&
1004                     !($pkg->{'Builder'} =~ /^(\w+)-\w+/ && $1 eq $user)) {
1005                 print "$name: not taken by you, but by ".
1006                           "$pkg->{'Builder'}. Skipping.\n";
1007                 return;
1008         }
1009         if (!pkg_version_eq($pkg, $version)) {
1010                 print "$name: version mismatch ($pkg->{'Version'} registered). ",
1011                           "Skipping.\n";
1012                 return;
1013         }
1014         change_state( \$pkg, 'Needs-Build' );
1015         delete $pkg->{'Builder'};
1016         delete $pkg->{'Depends'};
1017         log_ta( $pkg, "--give-back" );
1018         $db{$name} = $pkg;
1019         print "$name: given back\n" if $verbose;
1020 }
1021
1022 sub set_one_binnmu {
1023         my $name = shift;
1024         my $version = shift;
1025         my $pkg = $db{$name};
1026         my $state;
1027
1028         if (!defined($pkg)) {
1029                 print "$name: not registered; can't register for binNMU.\n";
1030                 return;
1031         }
1032         my $db_ver = $pkg->{'Version'};
1033
1034         if (!version_eq($db_ver, $version)) {
1035                 print "$name: version mismatch ($db_ver registered). ",
1036                           "Skipping.\n";
1037                 return;
1038         }
1039         $state = $pkg->{'State'};
1040
1041         if (defined $pkg->{'Binary-NMU-Version'}) {
1042                 if ($binNMUver == 0) {
1043                         change_state( \$pkg, 'Installed' );
1044                         delete $pkg->{'Builder'};
1045                         delete $pkg->{'Depends'};
1046                         delete $pkg->{'Binary-NMU-Version'};
1047                         delete $pkg->{'Binary-NMU-Changelog'};
1048                 } elsif ($binNMUver <= $pkg->{'Binary-NMU-Version'}) {
1049                         print "$name: already building binNMU $pkg->{'Binary-NMU-Version'}\n";
1050                         return;
1051                 } else {
1052                         $pkg->{'Binary-NMU-Version'} = $binNMUver;
1053                         $pkg->{'Binary-NMU-Changelog'} = $fail_reason;
1054                         $pkg->{'Notes'} = 'out-of-date';
1055                         $pkg->{'BuildPri'} = $pkg->{'PermBuildPri'}
1056                                 if (defined $pkg->{'PermBuildPri'});
1057                 }
1058                 log_ta( $pkg, "--binNMU" );
1059                 $db{$name} = $pkg;
1060                 return;
1061         } elsif ($binNMUver == 0) {
1062                 print "${name}_$version: no scheduled binNMU to cancel.\n";
1063                 return;
1064         }
1065
1066         if ($state ne 'Installed') {
1067                 print "${name}_$version: not installed; can't register for binNMU.\n";
1068                 return;
1069         }
1070
1071         my $fullver = binNMU_version($version,$binNMUver);
1072         if ( version_lesseq( $fullver, $pkg->{'Installed-Version'} ) )
1073         {
1074                 print "$name: binNMU $fullver is not newer than current version $pkg->{'Installed-Version'}\n";
1075                 return;
1076         }
1077
1078         change_state( \$pkg, 'Needs-Build' );
1079         delete $pkg->{'Builder'};
1080         delete $pkg->{'Depends'};
1081         $pkg->{'Binary-NMU-Version'} = $binNMUver;
1082         $pkg->{'Binary-NMU-Changelog'} = $fail_reason;
1083         $pkg->{'Notes'} = 'out-of-date';
1084         log_ta( $pkg, "--binNMU" );
1085         $db{$name} = $pkg;
1086         print "${name}: registered for binNMU $fullver\n" if $verbose;
1087 }
1088
1089 sub set_one_buildpri {
1090         my $name = shift;
1091         my $version = shift;
1092         my $key = shift;
1093         my $pkg = $db{$name};
1094         my $state;
1095
1096         if (!defined($pkg)) {
1097                 print "$name: not registered; can't set priority.\n";
1098                 return;
1099         }
1100         $state = $pkg->{'State'};
1101
1102         if ($state eq "Not-For-Us") {
1103                 print "$name: not suitable for this architecture. Skipping.\n";
1104                 return;
1105         } elsif ($state eq "Failed-Removed") {
1106                 print "$name: failed previously and doesn't need building. Skipping.\n";
1107                 return;
1108         }
1109         if (!pkg_version_eq($pkg, $version)) {
1110                 print "$name: version mismatch ($pkg->{'Version'} registered). ",
1111                           "Skipping.\n";
1112                 return;
1113         }
1114         if ( $build_priority == 0 ) {
1115                 delete $pkg->{'BuildPri'}
1116                         if $key eq 'PermBuildPri' and defined $pkg->{'BuildPri'}
1117                         and $pkg->{'BuildPri'} == $pkg->{$key};
1118                 delete $pkg->{$key};
1119         } else {
1120                 $pkg->{'BuildPri'} = $build_priority
1121                         if $key eq 'PermBuildPri';
1122                 $pkg->{$key} = $build_priority;
1123         }
1124         $db{$name} = $pkg;
1125         print "$name: set to build priority $build_priority\n" if $verbose;
1126 }
1127
1128 sub add_one_depwait {
1129         my $name = shift;
1130         my $version = shift;
1131         my $state;
1132         my $pkg = $db{$name};
1133
1134         if (!defined($pkg)) {
1135                 print "$name: not registered yet.\n";
1136                 return;
1137         }
1138         $state = $pkg->{'State'};
1139
1140         if ($state eq "Dep-Wait") {
1141                 print "$name: merging with previously registered dependencies\n";
1142         }
1143         
1144         if (isin( $state, qw(Needs-Build Failed BD-Uninstallable))) {
1145                 print "$name: Warning: not registered for building previously, ".
1146                           "but processing anyway.\n";
1147         }
1148         elsif ($state eq "Not-For-Us") {
1149                 print "$name: not suitable for this architecture anyway. Skipping.\n";
1150                 return;
1151         }
1152         elsif ($state eq "Failed-Removed") {
1153                 print "$name: failed previously and doesn't need building. Skipping.\n";
1154                 return;
1155         }
1156         elsif ($state eq "Installed") {
1157                 print "$name: Is already installed in archive. Skipping.\n";
1158                 return;
1159         }
1160         elsif ($state eq "Uploaded") {
1161                 print "$name: Is already uploaded. Skipping.\n";
1162                 return;
1163         }
1164         elsif ($pkg->{'Builder'} &&
1165                    $user ne $pkg->{'Builder'}) {
1166                 print "$name: not taken by you, but by ".
1167                           "$pkg->{'Builder'}. Skipping.\n";
1168                 return;
1169         }
1170         elsif ( !pkg_version_eq($pkg,$version)) {
1171                 print "$name: version mismatch ".
1172                           "($pkg->{'Version'} ".
1173                           "by $pkg->{'Builder'})\n";
1174                 return;
1175         }
1176         elsif ($fail_reason =~ /^\s*$/ ||
1177                    !parse_deplist( $fail_reason, 1 )) {
1178                 print "$name: Bad dependency list\n";
1179                 return;
1180         }
1181         change_state( \$pkg, 'Dep-Wait' );
1182         $pkg->{'Builder'} = $user;
1183         if (defined $pkg->{'PermBuildPri'}) {
1184                 $pkg->{'BuildPri'} = $pkg->{'PermBuildPri'};
1185         } else {
1186                 delete $pkg->{'BuildPri'};
1187         }
1188         my $deplist = parse_deplist( $pkg->{'Depends'} );
1189         my $new_deplist = parse_deplist( $fail_reason );
1190         # add new dependencies, maybe overwriting old entries
1191         foreach (keys %$new_deplist) {
1192                 $deplist->{$_} = $new_deplist->{$_};
1193         }
1194         $pkg->{'Depends'} = build_deplist($deplist);
1195         log_ta( $pkg, "--dep-wait" );
1196         $db{$name} = $pkg;
1197         print "$name: registered as waiting for dependencies\n" if $verbose;
1198 }
1199
1200
1201 sub parse_sources {
1202         my %pkgs;
1203         my %srcver;
1204         my $name;
1205         my $full = shift;
1206
1207         local($/) = ""; # read in paragraph mode
1208         while( <> ) {
1209                 my( $version, $arch, $section, $priority, $builddep, $buildconf, $binaries );
1210                 s/\s*$//m;
1211                 /^Package:\s*(\S+)$/mi and $name = $1;
1212                 /^Version:\s*(\S+)$/mi and $version = $1;
1213                 /^Architecture:\s*(\S+)$/mi and $arch = $1;
1214                 /^Section:\s*(\S+)$/mi and $section = $1;
1215                 /^Priority:\s*(\S+)$/mi and $priority = $1;
1216                 /^Build-Depends:\s*(.*)$/mi and $builddep = $1;
1217                 /^Build-Conflicts:\s*(.*)$/mi and $buildconf = $1;
1218                 /^Binary:\s*(.*)$/mi and $binaries = $1;
1219
1220                 next if (defined $srcver{$name} and version_less( $version, $srcver{$name} ));
1221                 $srcver{$name} = $version;
1222                 if ($buildconf) {
1223                     $buildconf = join( ", ", map { "!$_" } split( /\s*,\s*/, $buildconf ));
1224                     if ($builddep) {
1225                         $builddep .= "," . $buildconf;
1226                     } else {
1227                         $builddep = $buildconf;
1228                     }
1229                 }
1230
1231                 $pkgs{$name}{'dep'} = defined $builddep ? $builddep : "";
1232                 $pkgs{$name}{'ver'} = $version;
1233                 $pkgs{$name}{'bin'} = $binaries;
1234                 my $pkg = $db{$name};
1235
1236                 if (defined $pkg) {
1237                         my $change = 0;
1238
1239                         if ($arch eq "all" && !version_less( $version, $pkg->{'Version'} )) {
1240                                 # package is now Arch: all, delete it from db
1241                                 change_state( \$pkg, 'deleted' );
1242                                 log_ta( $pkg, "--merge-sources" );
1243                                 print "$name ($pkg->{'Version'}): deleted ".
1244                                           "from database, because now Arch: all\n"
1245                                                   if $verbose;
1246                                 delete $db{$name};
1247                                 next;
1248                         }
1249
1250                         # The "Version" should always be the source version --
1251                         # not a possible binNMU version number.
1252                         $pkg->{'Version'} = $version, $change++
1253                                 if ($pkg->{'State'} eq 'Installed' and
1254                                 !version_eq( $pkg->{'Version'}, $version));
1255                         # Always update priority and section, if available
1256                         $pkg->{'Priority'} = $priority, $change++
1257                                 if defined $priority and (not defined($pkg->{'Priority'}) or $pkg->{'Priority'} ne $priority);
1258
1259                         $pkg->{'Section'} = $section, $change++
1260                                 if defined $section and (not defined($pkg->{'Section'}) or $pkg->{'Section'} ne $section);
1261                         $db{$name} = $pkg if $change;
1262                 }
1263         }
1264         # Now that we only have the latest source version, build the list
1265         # of binary packages from the Sources point of view
1266         foreach $name (keys %pkgs) {
1267             foreach my $bin (split( /\s*,\s*/, $pkgs{$name}{'bin'} ) ) {
1268                 $merge_binsrc{$bin} = $name;
1269             }
1270         }
1271         # remove installed packages that no longer have source available
1272         # or binaries installed
1273         foreach $name (keys %db) {
1274                 next if $name =~ /^_/;
1275                 my $pkg = $db{$name};
1276                 if (not defined($pkgs{$name})) {
1277                         change_state( \$pkg, 'deleted' );
1278                         log_ta( $pkg, "--merge-sources" );
1279                         print "$name ($pkg->{'Version'}): ".
1280                                   "deleted from database, because ".
1281                                   "not in Sources anymore\n"
1282                                           if $verbose;
1283                         delete $db{$name};
1284                 } else {
1285                         next if !isin( $pkg->{'State'}, qw(Installed) );
1286                         if ($full && not defined $merge_srcvers{$name}) {
1287                             change_state( \$pkg, 'deleted' );
1288                             log_ta( $pkg, "--merge-sources" );
1289                             print "$name ($pkg->{'Version'}): ".
1290                                       "deleted from database, because ".
1291                                       "binaries don't exist anymore\n"
1292                                               if $verbose;
1293                             delete $db{$name};
1294                         } elsif ($full && version_less( $merge_srcvers{$name}, $pkg->{'Version'})) {
1295                             print "$name ($pkg->{'Version'}): ".
1296                                       "package is Installed but binaries are from ".
1297                                       $merge_srcvers{$name}. "\n"
1298                                               if $verbose;
1299                         }
1300                 }
1301         }
1302         return \%pkgs;
1303 }
1304
1305 # This function looks through a Packages file and sets the state of
1306 # packages to 'Installed'
1307 sub parse_packages {
1308         my $installed;
1309
1310         local($/) = ""; # read in paragraph mode
1311         while( <> ) {
1312                 my( $name, $version, $depends, $source, $sourcev, $architecture, $provides, $binaryv, $binnmu );
1313                 s/\s*$//m;
1314                 /^Package:\s*(\S+)$/mi and $name = $1;
1315                 /^Version:\s*(\S+)$/mi and $version = $1;
1316                 /^Depends:\s*(.*)$/mi and $depends = $1;
1317                 /^Source:\s*(\S+)(\s*\((\S+)\))?$/mi and ($source,$sourcev) = ($1, $3);
1318                 /^Architecture:\s*(\S+)$/mi and $architecture = $1;
1319                 /^Provides:\s*(.*)$/mi and $provides = $1;
1320                 next if !$name || !$version;
1321                 next if ($arch ne $architecture and $architecture ne "all");
1322                 next if (defined ($installed->{$name}) and $installed->{$name}{'Version'} ne "" and
1323                         version_lesseq( $version, $installed->{$name}{'Version'} ));
1324                 $installed->{$name}{'Version'} = $version;
1325                 $installed->{$name}{'Depends'} = $depends;
1326                 $installed->{$name}{'all'} = 1 if $architecture eq "all";
1327                 undef $installed->{$name}{'Provider'};
1328                 $installed->{$name}{'Source'} = $source ? $source : $name;
1329                 if ($provides) {
1330                     foreach (split( /\s*,\s*/, $provides )) {
1331                         if (not defined ($installed->{$_})) {
1332                             $installed->{$_}{'Version'} = "";
1333                             $installed->{$_}{'Provider'} = $name;
1334                         }
1335                     }
1336                 }
1337                 if ( $version =~ /\+b(\d+)$/ ) {
1338                     $binnmu = $1;
1339                 }
1340                 $version = $sourcev if $sourcev;
1341                 $binaryv = $version;
1342                 $binaryv =~ s/\+b\d+$//;
1343                 $installed->{$name}{'Sourcev'} = $sourcev ? $sourcev : $binaryv;
1344                 $binaryv .= "+b$binnmu" if defined($binnmu);
1345
1346                 next if $architecture ne $arch;
1347                 $name = $source if $source;
1348                 next if defined($merge_srcvers{$name}) and $merge_srcvers{$name} eq $version;
1349                 $merge_srcvers{$name} = $version;
1350
1351                 my $pkg = $db{$name};
1352
1353                 if (defined $pkg) {
1354                         if (isin( $pkg->{'State'}, qw(Not-For-Us)) ||
1355                                 (isin($pkg->{'State'}, qw(Installed)) &&
1356                                  version_lesseq($binaryv, $pkg->{'Installed-Version'}))) {
1357                                 print "Skipping $name because State == $pkg->{'State'}\n"
1358                                         if $verbose >= 2;
1359                                 next;
1360                         }
1361                         if ($pkg->{'Binary-NMU-Version'} ) {
1362                                 my $nmuver = binNMU_version($pkg->{'Version'}, $pkg->{'Binary-NMU-Version'});
1363                                 if (version_less( $binaryv, $nmuver )) {
1364                                         print "Skipping $name ($version) because have newer ".
1365                                                 "version ($nmuver) in db.\n"
1366                                                         if $verbose >= 2;
1367                                         next;
1368                                 }
1369                         } elsif (version_less($version, $pkg->{'Version'})) {
1370                                 print "Skipping $name ($version) because have newer ".
1371                                         "version ($pkg->{'Version'}) in db.\n"
1372                                                 if $verbose >= 2;
1373                                 next;
1374                         }
1375
1376                         if (!pkg_version_eq($pkg, $version) &&
1377                            $pkg->{'State'} ne "Installed") {
1378                                 warn "Warning: $name: newer version than expected appeared ".
1379                                          "in archive ($version vs. $pkg->{'Version'})\n";
1380                                 delete $pkg->{'Builder'};
1381                         }
1382
1383                         if (!isin( $pkg->{'State'}, qw(Uploaded) )) {
1384                                 warn "Warning: Package $name was not in uploaded state ".
1385                                          "before (but in '$pkg->{'State'}').\n";
1386                                 delete $pkg->{'Builder'};
1387                                 delete $pkg->{'Depends'};
1388                         }
1389                 } else {
1390                         $pkg = {};
1391                         $pkg->{'Version'} = $version;
1392                 }
1393                 
1394                 change_state( \$pkg, 'Installed' );
1395                 $pkg->{'Package'} = $name;
1396                 $pkg->{'Installed-Version'} = $binaryv;
1397                 if (defined $pkg->{'PermBuildPri'}) {
1398                         $pkg->{'BuildPri'} = $pkg->{'PermBuildPri'};
1399                 } else {
1400                         delete $pkg->{'BuildPri'};
1401                 }
1402                 $pkg->{'Version'} = $version
1403                         if version_less( $pkg->{'Version'}, $version);
1404                 delete $pkg->{'Binary-NMU-Version'};
1405                 delete $pkg->{'Binary-NMU-Changelog'};
1406                 log_ta( $pkg, "--merge-packages" );
1407                 $db{$name} = $pkg;
1408                 print "$name ($version) is up-to-date now.\n" if $verbose;
1409         }
1410
1411         check_dep_wait( "--merge-packages", $installed );
1412         return $installed;
1413 }
1414
1415 sub pretend_avail {
1416         my ($package, $name, $version, $installed);
1417         
1418         foreach $package (@_) {
1419                 $package =~ s,^.*/,,; # strip path
1420                 $package =~ s/\.(dsc|diff\.gz|tar\.gz|deb)$//; # strip extension
1421                 $package =~ s/_[\w\d]+\.changes$//; # strip extension
1422                 if ($package =~ /^([\w\d.+-]+)_([\w\d:.+~-]+)/) {
1423                         ($name,$version) = ($1,$2);
1424                 }
1425                 else {
1426                         warn "$package: can't extract package name and version ".
1427                                  "(bad format)\n";
1428                         next;
1429                 }
1430                 $installed->{$name}{'Version'} = $version;
1431         }
1432
1433         check_dep_wait( "--pretend-avail", $installed );
1434 }
1435
1436 sub check_dep_wait {
1437         my $action = shift;
1438         my $installed = shift;
1439         
1440         # check all packages in state Dep-Wait if dependencies are all
1441         # available now
1442         my $name;
1443         foreach $name (keys %db) {
1444                 next if $name =~ /^_/;
1445                 my $pkg = $db{$name};
1446                 next if $pkg->{'State'} ne "Dep-Wait";
1447                 my $deps = $pkg->{'Depends'};
1448                 if (!$deps) {
1449                         print "$name: was in state Dep-Wait, but with empty ",
1450                                   "dependencies!\n";
1451                         goto make_needs_build;
1452                 }
1453                 my $deplist = parse_deplist($deps);
1454                 my $new_deplist;
1455                 my $allok = 1;
1456                 my @removed_deps;
1457                 foreach (keys %$deplist) {
1458                         if (!exists $installed->{$_} ||
1459                                 ($deplist->{$_}->{'Rel'} && $deplist->{$_}->{'Version'} &&
1460                                  !version_compare( $installed->{$_}{'Version'},
1461                                                                    $deplist->{$_}->{'Rel'},
1462                                                                    $deplist->{$_}->{'Version'}))) {
1463                                 $allok = 0;
1464                                 $new_deplist->{$_} = $deplist->{$_};
1465                         }
1466                         else {
1467                                 push( @removed_deps, $_ );
1468                         }
1469                 }
1470                 if ($allok) {
1471                   make_needs_build:
1472                         change_state( \$pkg, 'Needs-Build' );
1473                         log_ta( $pkg, $action );
1474                         delete $pkg->{'Builder'};
1475                         delete $pkg->{'Depends'};
1476                         print "$name ($pkg->{'Version'}) has all ",
1477                                   "dependencies available now\n" if $verbose;
1478                         $new_vers{$name}++;
1479                         $db{$name} = $pkg;
1480                 }
1481                 elsif (@removed_deps) {
1482                         $pkg->{'Depends'} = build_deplist( $new_deplist );
1483                         print "$name ($pkg->{'Version'}): some dependencies ",
1484                                   "(@removed_deps) available now, but not all yet\n"
1485                                 if $verbose;
1486                         $db{$name} = $pkg;
1487                 }
1488         }
1489 }
1490
1491 # This function accepts quinn-diff output (either from a file named on
1492 # the command line, or on stdin) and sets the packages named there to
1493 # state 'Needs-Build'.
1494 sub parse_quinn_diff {
1495         my $partial = shift;
1496         my %quinn_pkgs;
1497         my $dubious = "";
1498         
1499         while( <> ) {
1500                 my $change = 0;
1501                 next if !m,^([-\w\d/]*)/                        # section
1502                                ([-\w\d.+]+)_                    # package name
1503                                    ([\w\d:.~+-]+)\.dsc\s*       # version
1504                                    \[([^:]*):                           # priority
1505                                    ([^]]+)\]\s*$,x;                     # rest of notes
1506                 my($section,$name,$version,$priority,$notes) = ($1, $2, $3, $4, $5);
1507                 $quinn_pkgs{$name}++;
1508                 $section ||= "unknown";
1509                 $priority ||= "unknown";
1510                 $priority = "unknown" if $priority eq "-";
1511                 $priority = "standard" if ($name eq "debian-installer");
1512
1513                 my $pkg = $db{$name};
1514
1515                 # Always update section and priority.
1516                 if (defined($pkg)) {
1517
1518                         $pkg->{'Section'}  = $section, $change++ if not defined
1519                                 $pkg->{'Section'} or $section ne "unknown";
1520                         $pkg->{'Priority'} = $priority, $change++ if not defined
1521                                 $pkg->{'Priority'} or $priority ne "unknown";
1522                 }
1523
1524                 if (defined($pkg) &&
1525                         $pkg->{'State'} =~ /^Dep-Wait/ &&
1526                         version_less( $pkg->{'Version'}, $version )) {
1527                         change_state( \$pkg, 'Dep-Wait' );
1528                         $pkg->{'Version'}  = $version;
1529                         delete $pkg->{'Binary-NMU-Version'};
1530                         delete $pkg->{'Binary-NMU-Changelog'};
1531                         log_ta( $pkg, "--merge-quinn" );
1532                         $change++;
1533                         print "$name ($version) still waiting for dependencies.\n"
1534                                 if $verbose;
1535                 }
1536                 elsif (defined($pkg) &&
1537                            $pkg->{'State'} =~ /-Removed$/ &&
1538                            version_eq($pkg->{'Version'}, $version)) {
1539                         # reinstantiate a package that has been removed earlier
1540                         # (probably due to a quinn-diff malfunction...)
1541                         my $newstate = $pkg->{'State'};
1542                         $newstate =~ s/-Removed$//;
1543                         change_state( \$pkg, $newstate );
1544                         $pkg->{'Version'}  = $version;
1545                         $pkg->{'Notes'}    = $notes;
1546                         log_ta( $pkg, "--merge-quinn" );
1547                         $change++;
1548                         print "$name ($version) reinstantiated to $newstate.\n"
1549                                 if $verbose;
1550                 }
1551                 elsif (defined($pkg) &&
1552                            $pkg->{'State'} eq "Not-For-Us" &&
1553                            version_less( $pkg->{'Version'}, $version )) {
1554                         # for Not-For-Us packages just update the version etc., but
1555                         # keep the state
1556                         change_state( \$pkg, "Not-For-Us" );
1557                         $pkg->{'Package'}  = $name;
1558                         $pkg->{'Version'}  = $version;
1559                         $pkg->{'Notes'}    = $notes;
1560                         delete $pkg->{'Builder'};
1561                         log_ta( $pkg, "--merge-quinn" );
1562                         $change++;
1563                         print "$name ($version) still Not-For-Us.\n" if $verbose;
1564                 }
1565                 elsif (!defined($pkg) ||
1566                            $pkg->{'State'} ne "Not-For-Us" &&
1567                            (version_less( $pkg->{'Version'}, $version ) ||
1568                            ($pkg->{'State'} eq "Installed" && version_less($pkg->{'Installed-Version'}, $version)))) {
1569
1570                         if (defined( $pkg->{'State'} ) && isin( $pkg->{'State'}, qw(Building Built Build-Attempted))) {
1571                                 send_mail( $pkg->{'Builder'},
1572                                                    "new version of $name (dist=$distribution)",
1573                                                    "As far as I'm informed, you're currently ".
1574                                                    "building the package $name\n".
1575                                                    "in version $pkg->{'Version'}.\n\n".
1576                                                    "Now there's a new source version $version. ".
1577                                                    "If you haven't finished\n".
1578                                                    "compiling $name yet, you can stop it to ".
1579                                                    "save some work.\n".
1580                                                    "Just to inform you...\n".
1581                                                    "(This is an automated message)\n" );
1582                                 print "$name: new version ($version) while building ".
1583                                           "$pkg->{'Version'} -- sending mail ".
1584                                           "to builder ($pkg->{'Builder'})\n"
1585                                   if $verbose;
1586                         }
1587                         change_state( \$pkg, 'Needs-Build' );
1588                         $pkg->{'Package'}  = $name;
1589                         $pkg->{'Version'}  = $version;
1590                         $pkg->{'Section'}  = $section;
1591                         $pkg->{'Priority'} = $priority;
1592                         $pkg->{'Notes'}    = $notes;
1593                         delete $pkg->{'Builder'};
1594                         delete $pkg->{'Binary-NMU-Version'};
1595                         delete $pkg->{'Binary-NMU-Changelog'};
1596                         log_ta( $pkg, "--merge-quinn" );
1597                         $new_vers{$name}++;
1598                         $change++;
1599                         print "$name ($version) needs rebuilding now.\n" if $verbose;
1600                 }
1601                 elsif (defined($pkg) &&
1602                            !version_eq( $pkg->{'Version'}, $version ) &&
1603                            isin( $pkg->{'State'}, qw(Installed Not-For-Us) )) {
1604                         print "$name: skipping because version in db ".
1605                                   "($pkg->{'Version'}) is >> than ".
1606                                   "what quinn-diff says ($version) ".
1607                                   "(state is $pkg->{'State'})\n"
1608                                           if $verbose;
1609                         $dubious .= "$pkg->{'State'}: ".
1610                                                 "db ${name}_$pkg->{'Version'} >> ".
1611                                                 "quinn $version\n" if !$partial;
1612                 }
1613                 elsif ($verbose >= 2) {
1614                         if ($pkg->{'State'} eq "Not-For-Us") {
1615                                 print "Skipping $name because State == ".
1616                                           "$pkg->{'State'}\n";
1617                         }
1618                         elsif (!version_less($pkg->{'Version'}, $version)) {
1619                                 print "Skipping $name because version in db ".
1620                                           "($pkg->{'Version'}) is >= than ".
1621                                           "what quinn-diff says ($version)\n";
1622                         }
1623                 }
1624                 $db{$name} = $pkg if $change;
1625         }
1626
1627         if ($dubious) {
1628                 send_mail( $conf::db_maint,
1629                                    "Dubious versions in $distribution $conf::dbbase database",
1630                                    "The following packages have a newer version in the ".
1631                                    "wanna-build database\n".
1632                                    "than what quinn-diff says, and this is strange for ".
1633                                    "their state\n".
1634                                    "It could be caused by a lame mirror, or the version ".
1635                                    "in the database\n".
1636                                    "is wrong.\n\n".
1637                                    $dubious );
1638         }
1639
1640         # Now re-check the DB for packages in states Needs-Build, Failed,
1641         # Dep-Wait or BD-Uninstallable and remove them if they're not listed
1642         # anymore by quinn-diff.
1643         if ( !$partial ) {
1644                 my $name;
1645                 foreach $name (keys %db) {
1646                         next if $name =~ /^_/;
1647                         my $pkg = $db{$name};
1648                         next if defined $pkg->{'Binary-NMU-Version'};
1649                         next if !isin( $pkg->{'State'},
1650                                                    qw(Needs-Build Building Built Build-Attempted Uploaded Failed Dep-Wait BD-Uninstallable) );
1651                         my $virtual_delete = $pkg->{'State'} eq 'Failed';
1652                                                                  
1653                         if (!$quinn_pkgs{$name}) {
1654                                 change_state( \$pkg, $virtual_delete ?
1655                                                           $pkg->{'State'}."-Removed" :
1656                                                           'deleted' );
1657                                 log_ta( $pkg, "--merge-quinn" );
1658                                 print "$name ($pkg->{'Version'}): ".
1659                                           ($virtual_delete ? "(virtually) " : "") . "deleted ".
1660                                           "from database, because not in quinn-diff anymore\n"
1661                                                   if $verbose;
1662                                 if ($virtual_delete) {
1663                                     $db{$name} = $pkg;
1664                                 } else {
1665                                     delete $db{$name};
1666                                 }
1667                         }
1668                 }
1669         }
1670 }
1671
1672 sub send_reupload_mail {
1673         my $to = shift;
1674         my $pkg = shift;
1675         my $version = shift;
1676         my $dist = shift;
1677         my $other_dist = shift;
1678
1679         send_mail( $to,
1680                            "Please reupload ${pkg}_${'Version'} for $dist",
1681                            "You have recently built (or are currently building)\n".
1682                            "${pkg}_${'Version'} for $other_dist.\n".
1683                            "This version is now also needed in the $dist distribution.\n".
1684                            "Please reupload the files now present in the Debian archive\n".
1685                            "(best with buildd-reupload).\n" );
1686 }
1687
1688
1689 # for sorting priorities and sections
1690 BEGIN {
1691         %prioval = ( required             => -5,
1692                                  important            => -4,
1693                                  standard             => -3,
1694                                  optional             => -2,
1695                                  extra                => -1,
1696                                  unknown              => -1 );
1697         %sectval = ( 
1698                                  libs                   => -200,
1699                                  'debian-installer'     => -199,
1700                                  base                   => -198,
1701                                  devel                  => -197,
1702                                  kernel                 => -196,
1703                                  shells                 => -195,
1704                                  perl                   => -194,
1705                                  python                 => -193,
1706                                  graphics               => -192,
1707                                  admin                  => -191,
1708                                  utils                  => -190,
1709                                  x11                    => -189,
1710                                  editors                => -188,
1711                                  net                    => -187,
1712                                  httpd                  => -186,
1713                                  mail                   => -185,
1714                                  news                   => -184,
1715                                  tex                    => -183,
1716                                  text                   => -182,
1717                                  web                    => -181,
1718                                  vcs                    => -180,
1719                                  doc                    => -179,
1720                                  localizations          => -178,
1721                                  interpreters           => -177,
1722                                  ruby                   => -176,
1723                                  java                   => -175,
1724                                  ocaml                  => -174,
1725                                  lisp                   => -173,
1726                                  haskell                => -172,
1727                                  'cli-mono'             => -171,
1728                                  gnome                  => -170,
1729                                  kde                    => -169,
1730                                  xfce                   => -168,
1731                                  gnustep                => -167,
1732                                  database               => -166,
1733                                  video                  => -165,
1734                                  debug                  => -164,
1735                                  games                  => -163,
1736                                  misc                   => -162,
1737                                  fonts                  => -161,
1738                                  otherosfs              => -160,
1739                                  oldlibs                => -159,
1740                                  libdevel               => -158,
1741                                  sound                  => -157,
1742                                  math                   => -156,
1743                                  'gnu-r'                => -155,
1744                                  science                => -154,
1745                                  comm                   => -153,
1746                                  electronics            => -152,
1747                                  hamradio               => -151,
1748                                  embedded               => -150,
1749                                  php                    => -149,
1750                                  zope                   => -148,
1751         );
1752         foreach my $i (keys %sectval) {
1753                 $sectval{"contrib/$i"} = $sectval{$i}+40;
1754                 $sectval{"non-free/$i"} = $sectval{$i}+80;
1755         }
1756         $sectval{'unknown'}     = -165;
1757
1758         %catval =  ( "none"                           => -20,
1759                                  "uploaded-fixed-pkg" => -19,
1760                                  "fix-expected"       => -18,
1761                                  "reminder-sent"      => -17,
1762                                  "nmu-offered"        => -16,
1763                                  "easy"               => -15,
1764                                  "medium"                     => -14,
1765                                  "hard"                   => -13,
1766                                  "compiler-error"     => -12 );
1767 }
1768
1769 sub sort_list_func {
1770         my( $letter, $x, $ax, $bx );
1771
1772         foreach $letter (split( "", $list_order )) {
1773           SWITCH: foreach ($letter) {
1774                   /P/ && do {
1775                         $x = $b->{'BuildPri'} <=> $a->{'BuildPri'};
1776                         return $x if $x != 0;
1777                         last SWITCH;
1778                   };
1779                   /p/ && do {
1780                           $x = $prioval{$a->{'Priority'}} <=> $prioval{$b->{'Priority'}};
1781                           return $x if $x != 0;
1782                           last SWITCH;
1783                   };
1784                   /s/ && do {
1785                           $x = $sectval{$a->{'Section'}} <=> $sectval{$b->{'Section'}};
1786                           return $x if $x != 0;
1787                           last SWITCH;
1788                   };
1789                   /n/ && do {
1790                           $x = $a->{'Package'} cmp $b->{'Package'};
1791                           return $x if $x != 0;
1792                           last SWITCH;
1793                   };
1794                   /b/ && do {
1795                           $x = $a->{'Builder'} cmp $b->{'Builder'};
1796                           return $x if $x != 0;
1797                           last SWITCH;
1798                   };
1799                   /c/ && do {
1800                           $ax = ($a->{'Notes'} =~ /^(out-of-date|partial)/) ? 0 :
1801                                     ($a->{'Notes'} =~ /^uncompiled/) ? 2 : 1;
1802                           $bx = ($b->{'Notes'} =~ /^(out-of-date|partial)/) ? 0 :
1803                                     ($b->{'Notes'} =~ /^uncompiled/) ? 2 : 1;
1804                           $x = $ax <=> $bx;
1805                           return $x if $x != 0;
1806                           last SWITCH;
1807                   };
1808                   /f/ && do {
1809                           my $ca = exists $a->{'Failed-Category'} ?
1810                                   $a->{'Failed-Category'} : "none";
1811                           my $cb = exists $b->{'Failed-Category'} ?
1812                                   $b->{'Failed-Category'} : "none";
1813                           $x = $catval{$ca} <=> $catval{$cb};
1814                           return $x if $x != 0;
1815                           last SWITCH;
1816                   };
1817                   /S/ && do {
1818                           my $pa = $prioval{$a->{'Priority'}} >
1819                                   $prioval{'standard'};
1820                           my $pb = $prioval{$b->{'Priority'}} >
1821                                   $prioval{'standard'};
1822                           $x = $pa <=> $pb;
1823                           return $x if $x != 0;
1824                           last SWITCH;
1825                   };
1826           }
1827         }
1828         return 0;
1829 }
1830
1831 sub list_packages {
1832         my $state = shift;
1833         my( $name, $pkg, @list );
1834         my $cnt = 0;
1835         my %scnt;
1836         my $ctime = time;
1837
1838         foreach $name (keys %db) {
1839                 next if $name =~ /^_/;
1840                 $pkg = $db{$name};
1841                 next if $state ne "all" && $pkg->{'State'} !~ /^\Q$state\E$/i;
1842                 next if $user && (lc($state) ne 'needs-build' and $pkg->{'Builder'} ne $user);
1843                 next if $category && $pkg->{'State'} eq "Failed" &&
1844                                 $pkg->{'Failed-Category'} ne $category;
1845                 next if ($list_min_age > 0 &&
1846                                  ($ctime-parse_date($pkg->{'State-Change'})) < $list_min_age)||
1847                                 ($list_min_age < 0 &&
1848                                  ($ctime-parse_date($pkg->{'State-Change'})) > -$list_min_age);
1849                 push( @list, $pkg );
1850         }
1851
1852         foreach $pkg (sort sort_list_func @list) {
1853                 print "$pkg->{'Section'}/$pkg->{'Package'}_$pkg->{'Version'}";
1854                 print ": $pkg->{'State'}"
1855                         if $state eq "all";
1856                 print " by $pkg->{'Builder'}"
1857                         if $pkg->{'State'} ne "Needs-Build" && $pkg->{'Builder'};
1858                 print " [$pkg->{'Priority'}:$pkg->{'Notes'}";
1859                 print ":PREV-FAILED"
1860                         if $pkg->{'Previous-State'} =~ /^Failed/;
1861                 print ":bp{" . $pkg->{'BuildPri'} . "}"
1862                         if exists $pkg->{'BuildPri'};
1863                 print ":binNMU{" . $pkg->{'Binary-NMU-Version'} . "}"
1864                         if exists $pkg->{'Binary-NMU-Version'};
1865                 print "]\n";
1866                 print "  Reasons for failing:\n",
1867                           "    [Category: ",
1868                           exists $pkg->{'Failed-Category'} ? $pkg->{'Failed-Category'} : "none",
1869                           "]\n    ",
1870                           join("\n    ",split("\n",$pkg->{'Failed'})), "\n"
1871                         if $pkg->{'State'} =~ /^Failed/;
1872                 print "  Dependencies: $pkg->{'Depends'}\n"
1873                         if $pkg->{'State'} eq "Dep-Wait";
1874                 print "  Reason: $pkg->{'Reason'}\n"
1875                         if $pkg->{'State'} eq "BD-Uninstallable";
1876                 print "  Previous state was $pkg->{'Previous-State'} until ",
1877                           "$pkg->{'State-Change'}\n"
1878                         if $verbose && $pkg->{'Previous-State'};
1879                 print "  Previous failing reasons:\n    ",
1880                       join("\n    ",split("\n",$pkg->{'Old-Failed'})), "\n"
1881                         if $verbose && $pkg->{'Old-Failed'};
1882                 ++$cnt;
1883                 $scnt{$pkg->{'State'}}++ if $state eq "all";
1884         }
1885         if ($state eq "all") {
1886                 foreach (sort keys %scnt) {
1887                         print "Total $scnt{$_} package(s) in state $_.\n";
1888                 }
1889         }
1890         print "Total $cnt package(s)\n";
1891         
1892 }
1893
1894 sub info_packages {
1895         my( $name, $pkg, $key, $dist );
1896         my @firstkeys = qw(Package Version Builder State Section Priority
1897                                            Installed-Version Previous-State State-Change);
1898         my @dists = $info_all_dists ? keys %conf::distributions : ($distribution);
1899         
1900         foreach $dist (@dists) {
1901                 if ($dist ne $distribution) {
1902                         if (!-f db_filename( $dist ) || !open_other_db( $dist )) {
1903                                 warn "Cannot open database for $dist!\n";
1904                                 @dists = grep { $_ ne $dist } @dists;
1905                         }
1906                 }
1907         }
1908
1909         foreach $name (@_) {
1910                 $name =~ s/_.*$//; # strip version
1911                 foreach $dist (@dists) {
1912                         my $db = $dist ne $distribution ? $otherdb{$dist} : \%db;
1913                         my $pname = "$name" . ($info_all_dists ? "($dist)" : "");
1914                         
1915                         $pkg = $db->{$name};
1916                         if (!defined( $pkg )) {
1917                                 print "$pname: not registered\n";
1918                                 next;
1919                         }
1920
1921                         print "$pname:\n";
1922                         foreach $key (@firstkeys) {
1923                                 next if !exists $pkg->{$key};
1924                                 my $val = $pkg->{$key};
1925                                 chomp( $val );
1926                                 $val = "\n$val" if isin( $key, qw(Failed Old-Failed));
1927                                 $val =~ s/\n/\n    /g;
1928                                 printf "  %-20s: %s\n", $key, $val;
1929                         }
1930                         foreach $key (sort keys %$pkg) {
1931                                 next if isin( $key, @firstkeys );
1932                                 my $val = $pkg->{$key};
1933                                 chomp( $val );
1934                                 $val = "\n$val" if isin( $key, qw(Failed Old-Failed));
1935                                 $val =~ s/\n/\n    /g;
1936                                 printf "  %-20s: %s\n", $key, $val;
1937                         }
1938                 }
1939         }
1940 }
1941
1942 sub forget_packages {
1943         my( $name, $pkg, $key, $data );
1944         
1945         foreach $name (@_) {
1946                 $name =~ s/_.*$//; # strip version
1947                 $pkg = $db{$name};
1948                 if (!defined( $pkg )) {
1949                         print "$name: not registered\n";
1950                         next;
1951                 }
1952
1953                 $data = "";
1954                 foreach $key (sort keys %$pkg) {
1955                         my $val = $pkg->{$key};
1956                         chomp( $val );
1957                         $val =~ s/\n/\n /g;
1958                         $data .= sprintf "  %-20s: %s\n", $key, $val;
1959                 }
1960                 send_mail( $conf::db_maint,
1961                                    "$name deleted from DB $conf::dbbase",
1962                                    "The package '$name' has been deleted from the database ".
1963                                    "by $user.\n\n".
1964                                    "Data registered about the deleted package:\n".
1965                                    "$data\n" ) if $conf::db_maint;
1966                 change_state( \$pkg, 'deleted' );
1967                 log_ta( $pkg, "--forget" );
1968                 delete $db{$name};
1969                 print "$name: deleted from database\n" if $verbose;
1970         }
1971 }
1972
1973 sub forget_users {
1974         my( $name, $ui );
1975         my $change = 0;
1976         
1977         $ui = $db{'_userinfo'};
1978         foreach $name (@_) {
1979                 if (!defined( $ui->{$name} )) {
1980                         print "$name: not registered\n";
1981                         next;
1982                 }
1983
1984                 delete $ui->{$name};
1985                 $change++;
1986                 print "$name: deleted from database\n" if $verbose;
1987         }
1988         $db{'_userinfo'} = $ui if $change;
1989 }
1990
1991 sub lock_db {
1992         my $dist = shift;
1993         my $try = 0;
1994         my $lockfile = db_lockfilename($dist);
1995         local( *F );
1996         
1997         print "Locking $dist database\n" if $verbose >= 2;
1998   repeat:
1999         if (!sysopen( F, $lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644 )){
2000                 if ($! == EEXIST) {
2001                         # lock file exists, wait
2002                         goto repeat if !open( F, "<$lockfile" );
2003                         my $line = <F>;
2004                         close( F );
2005                         if ($line !~ /^(\d+)\s+([\w\d.-]+)$/) {
2006                                 warn "Bad lock file contents -- still trying\n";
2007                         }
2008                         else {
2009                                 my($pid, $usr) = ($1, $2);
2010                                 if (kill( 0, $pid ) == 0 && $! == ESRCH) {
2011                                         # process doesn't exist anymore, remove stale lock
2012                                         print "Removing stale lock file (pid $pid, user $usr)\n";
2013                                         unlink( $lockfile );
2014                                         goto repeat;
2015                                 }
2016                                 if ($pid == $lock_for_pid) {
2017                                         # We are allowed to use this lock.
2018                                         return;
2019                                 }
2020                                 warn "Database locked by $usr -- please wait\n" if $try == 0;
2021                         }
2022                         if (++$try > 200) {
2023                                 # avoid the END routine removes the lock
2024                                 $main::keep_lock{$dist} = 1;
2025                                 die "Lock still present after 200 * 5 seconds.\n";
2026                         }
2027                         sleep 5;
2028                         goto repeat;
2029                 }
2030                 die "Can't create lock file $lockfile: $!\n";
2031         }
2032         my $pid = $lock_for_pid == -1 ? $$ : $lock_for_pid;
2033         F->print("$pid $real_user\n");
2034         F->close();
2035 }
2036
2037 sub unlock_db {
2038         my $dist = shift;
2039         my $lockfile = db_lockfilename($dist);
2040
2041         if (!$main::keep_lock{$dist}) {
2042                 print "Unlocking $dist database\n" if $verbose >= 2;
2043                 unlink $lockfile;
2044         }
2045 }
2046
2047 sub create_maintlock {
2048         my $lockfile = db_lockfilename("maintenance");
2049         my $try = 0;
2050         local( *F );
2051         
2052         print "Creating maintenance lock\n" if $verbose >= 2;
2053   repeat:
2054         if (!sysopen( F, $lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644 )){
2055                 if ($! == EEXIST) {
2056                         # lock file exists, wait
2057                         goto repeat if !open( F, "<$lockfile" );
2058                         my $line = <F>;
2059                         close( F );
2060                         if ($line !~ /^(\d+)\s+([\w\d.-]+)$/) {
2061                                 warn "Bad maintenance lock file contents -- still trying\n";
2062                         }
2063                         else {
2064                                 my($pid, $usr) = ($1, $2);
2065                                 if (kill( 0, $pid ) == 0 && $! == ESRCH) {
2066                                         # process doesn't exist anymore, remove stale lock
2067                                         print "Removing stale lock file (pid $pid, user $usr)\n";
2068                                         unlink( $lockfile );
2069                                         goto repeat;
2070                                 }
2071                                 warn "Maintenance lock already exists by $usr -- ".
2072                                          "please wait\n" if $try == 0;
2073                         }
2074                         if (++$try > 120) {
2075                                 die "Lock still present after 120 * 60 seconds.\n";
2076                         }
2077                         sleep 60;
2078                         goto repeat;
2079                 }
2080                 die "Can't create maintenance lock $lockfile: $!\n";
2081         }
2082         F->print(getppid(), " $real_user\n");
2083         F->close();
2084 }
2085
2086 sub remove_maintlock {
2087         my $lockfile = db_lockfilename("maintenance");
2088
2089         print "Removing maintenance lock\n" if $verbose >= 2;
2090         unlink $lockfile;
2091 }
2092
2093 sub waitfor_maintlock {
2094         my $lockfile = db_lockfilename("maintenance");
2095         my $try = 0;
2096         local( *F );
2097         
2098         print "Checking for maintenance lock\n" if $verbose >= 2;
2099   repeat:
2100         if (open( F, "<$lockfile" )) {
2101                 my $line = <F>;
2102                 close( F );
2103                 if ($line !~ /^(\d+)\s+([\w\d.-]+)$/) {
2104                         warn "Bad maintenance lock file contents -- still trying\n";
2105                 }
2106                 else {
2107                         my($pid, $usr) = ($1, $2);
2108                         if (kill( 0, $pid ) == 0 && $! == ESRCH) {
2109                                 # process doesn't exist anymore, remove stale lock
2110                                 print "Removing stale maintenance lock (pid $pid, user $usr)\n";
2111                                 unlink( $lockfile );
2112                                 return;
2113                         }
2114                         warn "Databases locked for general maintenance by $usr -- ".
2115                                  "please wait\n" if $try == 0;
2116                 }
2117                 if (++$try > 120) {
2118                         die "Lock still present after 120 * 60 seconds.\n";
2119                 }
2120                 sleep 60;
2121                 goto repeat;
2122         }
2123 }
2124
2125
2126 sub read_db {
2127         my $file = shift;
2128
2129         print "Reading ASCII database from $file..." if $verbose >= 1;
2130         open( F, "<$file" ) or
2131                 die "Can't open database $file: $!\n";
2132
2133         local($/) = ""; # read in paragraph mode
2134         while( <F> ) {
2135                 my( %thispkg, $name );
2136                 s/[\s\n]+$//;
2137                 s/\n[ \t]+/\376\377/g;  # fix continuation lines
2138                 s/\376\377\s*\376\377/\376\377/og;
2139   
2140                 while( /^(\S+):[ \t]*(.*)[ \t]*$/mg ) {
2141                         my ($key, $val) = ($1, $2);
2142                         $val =~ s/\376\377/\n/g;
2143                         $thispkg{$key} = $val;
2144                 }
2145                 check_entry( \%thispkg );
2146                 # add to db
2147                 if (exists($thispkg{'Package'})) {
2148                         $name = $thispkg{'Package'};
2149                         $db{$name} = \%thispkg;
2150                 }
2151                 elsif(exists($thispkg{'User'})) {
2152                         my $userinfo = $db{'_userinfo'};
2153                         $userinfo = {} if (!defined($userinfo));
2154
2155                         $name = $thispkg{'User'};
2156                         $userinfo->{$name} = \%thispkg;
2157
2158                         $db{'_userinfo'} = $userinfo;
2159                  }
2160         }
2161         close( F );
2162         print "done\n" if $verbose >= 1;
2163 }
2164
2165 sub check_entry {
2166         my $pkg = shift;
2167         my $field;
2168
2169         return if $op_mode eq "manual-edit"; # no checks then
2170         
2171         # check for required fields
2172         if (exists $pkg->{'User'}) {
2173                 return;
2174         }
2175         if (!exists $pkg->{'Package'}) {
2176                 print STDERR "Bad entry: ",
2177                           join( "\n", map { "$_: $pkg->{$_}" } keys %$pkg ), "\n";
2178                 die "Database entry lacks Package or User: field\n";
2179         }
2180         if (!exists $pkg->{'Version'}) {
2181                 die "Database entry for $pkg->{'Package'} lacks Version: field\n";
2182         }
2183         # if no State: field, generate one (for old db compat)
2184         if (!exists($pkg->{'State'})) {
2185                 $pkg->{'State'} =
2186                         exists $pkg->{'Failed'} ? 'Failed' : 'Building';
2187         }
2188         # check state field
2189         die "Bad state $pkg->{'State'} of package $pkg->{Package}\n"
2190                 if !isin( $pkg->{'State'},
2191                                   qw(Needs-Build Building Built Build-Attempted Uploaded Installed Dep-Wait
2192                                          Failed Failed-Removed Not-For-Us BD-Uninstallable
2193                                          ) );
2194 }
2195
2196 sub write_db {
2197         my $file = shift;
2198         my($name,$pkg,$key);
2199         
2200         print "Writing ASCII database to $file..." if $verbose >= 1;
2201         open( F, ">$file" ) or
2202                 die "Can't open database $file: $!\n";
2203
2204         foreach $name (sort keys %db) {
2205                 my $pkg = $db{$name};
2206                 if ($name eq '_userinfo') {
2207                         foreach $user (sort keys %{$pkg}) {
2208                             my $ui = $pkg->{$user};
2209                             print F "User: $user\n"
2210                                 if (!defined($ui->{'User'}));
2211                             foreach $key (keys %{$ui}) {
2212                                 my $val = $ui->{$key};
2213                                 $val =~ s/\n*$//;
2214                                 $val =~ s/^/ /mg;
2215                                 $val =~ s/^ $/ ./mg;
2216                                 print F "$key: $val\n";
2217                             }
2218                             print F "\n";
2219                         }
2220                 }
2221                 else {
2222                         foreach $key (keys %{$pkg}) {
2223                                 my $val = $pkg->{$key};
2224                                 $val =~ s/\n*$//;
2225                                 $val =~ s/^/ /mg;
2226                                 $val =~ s/^ $/ ./mg;
2227                                 print F "$key: $val\n";
2228                         }
2229                         print F "\n";
2230                 }
2231         }
2232         close( F );
2233         print "done\n" if $verbose >= 1;
2234 }
2235
2236 sub change_state {
2237         my $pkgr = shift;
2238         my $pkg = $$pkgr;
2239         my $newstate = shift;
2240         my $for_dist = shift;
2241         my $db;
2242         if ($for_dist) {
2243                 return if !open_other_db( $for_dist );
2244                 $db = $otherdb{$for_dist};
2245                 $pkg = \$db{$pkg->{'Package'}};
2246         }
2247         else {
2248                 $db = \%db;
2249         }
2250         my $state = \$pkg->{'State'};
2251         
2252         return if defined($$state) and $$state eq $newstate;
2253         $pkg->{'Previous-State'} = $$state if defined($$state);
2254         $pkg->{'State-Change'} = $curr_date;
2255
2256         if (defined($$state) and $$state eq 'Failed') {
2257                 $pkg->{'Old-Failed'} =
2258                         "-"x20 . " $pkg->{'Version'} " . "-"x20 . "\n" .
2259                         $pkg->{'Failed'} . "\n" .
2260                         $pkg->{'Old-Failed'};
2261                 delete $pkg->{'Failed'};
2262                 delete $pkg->{'Failed-Category'};
2263         }
2264         if (defined($$state) and $$state eq 'BD-Uninstallable') {
2265                 delete $pkg->{'Reason'};
2266         }
2267         $$state = $newstate;
2268 }
2269
2270 sub open_other_db {
2271         my $dist = shift;
2272
2273         if (!tied(%{$otherdb{$dist}})) {
2274                 lock_db( $dist );
2275                 $otherdb_lock{$dist} = 1;
2276                 if (!(tie %{$otherdb{$dist}}, 'MLDBM', db_filename($dist), 0, 0664)){
2277                         warn "Serious warning: Cannot open database for $dist\n";
2278                         unlock_db( $dist );
2279                         $otherdb_lock{$dist} = 0;
2280                         return 0;
2281                 }
2282         }
2283         return 1;
2284 }
2285
2286 sub log_ta {
2287         my $pkg = shift;
2288         my $action = shift;
2289         my $db = \%db;
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         my $transactlog = db_transactlog( $distribution );
2300         if (!open( LOG, ">>$transactlog" )) {
2301                 warn "Can't open log file $transactlog: $!\n";
2302                 return;
2303         }
2304         print LOG "$curr_date: $str\n";
2305         close( LOG );
2306
2307         if (!($prevstate eq 'Failed' && $pkg->{'State'} eq 'Failed')) {
2308                 $str .= " (with --override)"
2309                         if $opt_override;
2310                 $mail_logs .= "$str\n";
2311         }
2312 }
2313
2314
2315 sub send_mail {
2316         my $to = shift;
2317         my $subject = shift;
2318         my $text = shift;
2319
2320         my $from = $conf::db_maint;
2321         my $domain = $conf::buildd_domain;
2322
2323         $from .= "\@$domain" if $from !~ /\@/;
2324
2325         $to .= '@' . $domain if $to !~ /\@/;
2326         $text =~ s/^\.$/../mg;
2327         local $SIG{'PIPE'} = 'IGNORE';
2328         open( PIPE,  "| $conf::mailprog -oem $to" )
2329                 or die "Can't open pipe to $conf::mailprog: $!\n";
2330         chomp $text;
2331         print PIPE "From: $from\n";
2332         print PIPE "Subject: $subject\n\n";
2333         print PIPE "$text\n";
2334         close( PIPE );
2335 }
2336
2337 sub db_filename {
2338         my $dist = shift;
2339         return $transactional ? db_filename_transaction($dist) : db_filename_master($dist);
2340 }
2341 sub db_filename_master {
2342         my $dist = shift;
2343         return "$conf::basedir/$conf::dbbase-$dist";
2344 }
2345 sub db_filename_transaction {
2346         my $dist = shift;
2347         return "$conf::basedir/$conf::dbbase-$dist-transaction";
2348 }
2349
2350 sub db_lockfilename {
2351         my $dist = shift;
2352         return db_filename_master($dist) . ".lock";
2353 }
2354
2355
2356 sub db_transactlog {
2357         my $dist = shift;
2358         return $transactional ? db_transactlog_transaction($dist) : db_transactlog_master($dist);
2359 }
2360 sub db_transactlog_master {
2361         my $dist = shift;
2362         $conf::dbbase =~ m#^([^/]+/)#;
2363         return "$conf::basedir/$1$conf::transactlog";
2364 }
2365 sub db_transactlog_transaction {
2366         my $dist = shift;
2367         $conf::dbbase =~ m#^([^/]+/)#;
2368         return "$conf::basedir/$1$conf::transactlog-$dist-transaction";
2369 }
2370
2371 # for parsing input to dep-wait
2372 sub parse_deplist {
2373     my $deps = shift;
2374     my $verify = shift;
2375     my %result;
2376     
2377     foreach (split( /\s*,\s*/, $deps )) {
2378         if ($verify) {
2379             # verification requires > starting prompts, no | crap
2380             if (!/^(\S+)\s*(\(\s*(>(?:[>=])?)\s*(\S+)\s*\))?\s*$/) {
2381                 return 0;
2382             }
2383             next;
2384         }
2385         my @alts = split( /\s*\|\s*/, $_ );
2386         # Anything with an | is ignored, as it can be configured on a
2387         # per-buildd basis what will be installed
2388         next if $#alts != 0;
2389         $_ = shift @alts;
2390
2391         if (!/^(\S+)\s*(\(\s*(>=|=|==|>|>>|<<|<=)\s*(\S+)\s*\))?\s*$/) {
2392             warn( "parse_deplist: bad dependency $_\n" );
2393             next;
2394         }
2395         my($dep, $rel, $relv) = ($1, $3, $4);
2396         $rel = ">>" if defined($rel) and $rel eq ">";
2397         $result{$dep}->{'Package'} = $dep;
2398         if ($rel && $relv) {
2399             $result{$dep}->{'Rel'} = $rel;
2400             $result{$dep}->{'Version'} = $relv;
2401         }
2402     }
2403     return 1 if $verify;
2404     return \%result;
2405 }
2406
2407 # for parsing Build-Depends from Sources
2408 sub parse_srcdeplist {
2409     my $pkg = shift;
2410     my $deps = shift;
2411     my $arch = shift;
2412     my $dep;
2413     my @results;
2414     
2415     foreach $dep (split( /\s*,\s*/, $deps )) {
2416         my @alts = split( /\s*\|\s*/, $dep );
2417         # Anything with an | is ignored, as it can be configured on a
2418         # per-buildd basis what will be installed
2419         next if $#alts != 0;
2420         $_ = shift @alts;
2421         if (!/^([^\s([]+)\s*(\(\s*([<=>]+)\s*(\S+)\s*\))?(\s*\[([^]]+)\])?/) {
2422             warn( "parse_srcdeplist: bad dependency $_\n" );
2423             next;
2424         }
2425         my($dep, $rel, $relv, $archlist) = ($1, $3, $4, $6);
2426         if ($archlist) {
2427             $archlist =~ s/^\s*(.*)\s*$/$1/;
2428             my @archs = split( /\s+/, $archlist );
2429             my ($use_it, $ignore_it, $include) = (0, 0, 0);
2430             foreach (@archs) {
2431                 if (/^!/) {
2432                     $ignore_it = 1 if substr($_, 1) eq $arch;
2433                 } else {
2434                     $use_it = 1 if $_ eq $arch;
2435                     $include = 1;
2436                 }
2437             }
2438             warn "Warning: inconsistent arch restriction on ",
2439                  "$pkg: $dep depedency\n"
2440                  if $ignore_it && $use_it;
2441             next if $ignore_it || ($include && !$use_it);
2442         }
2443         my $neg = 0;
2444         if ($dep =~ /^!/) {
2445             $dep =~ s/^!\s*//;
2446             $neg = 1;
2447         }
2448         my $result;
2449         $result->{'Package'} = $dep;
2450         $result->{'Neg'} = $neg;
2451         if ($rel && $relv) {
2452             $result->{'Rel'} = $rel;
2453             $result->{'Version'} = $relv;
2454         }
2455         push @results, $result;
2456     }
2457     return \@results;
2458 }
2459
2460 sub build_deplist {
2461         my $list = shift;
2462         my($key, $result);
2463         
2464         foreach $key (keys %$list) {
2465                 $result .= ", " if $result;
2466                 $result .= $key;
2467                 $result .= " ($list->{$key}->{'Rel'} $list->{$key}->{'Version'})"
2468                         if $list->{$key}->{'Rel'} && $list->{$key}->{'Version'};
2469         }
2470         return $result;
2471 }
2472
2473 sub clean_db {
2474         my %new_db;
2475         tie %new_db, 'MLDBM', db_filename( $distribution ) . ".new", GDBM_WRCREAT, 0664
2476                 or die "FATAL: Cannot create new database\n";
2477         %new_db = %db;
2478         untie %db or die "FATAL: Cannot untie old database\n";
2479         system ("cp " . db_filename( $distribution ) . ".new " .
2480                 db_filename( $distribution ) ) == 0
2481                 or die "FATAL: Cannot overwrite old database";
2482         unlink db_filename( $distribution ) . ".new";
2483         %db = %new_db;
2484 }
2485
2486
2487 sub get_unsatisfied_dep {
2488     my $bd  = shift;
2489     my $pkgs = shift;
2490     my $dep = shift;
2491     my $savedep = shift;
2492
2493     my $pkgname = $dep->{'Package'};
2494
2495     if (defined $pkgs->{$pkgname}{'Provider'}) {
2496         # provides.  leave them for buildd/sbuild.
2497         return "";
2498     }
2499
2500     # check cache
2501     return $pkgs->{$pkgname}{'Unsatisfied'} if $savedep and defined($pkgs->{$pkgname}{'Unsatisfied'});
2502
2503     # Return unsatisfied deps to a higher caller to process
2504     if ((!defined($pkgs->{$pkgname})) or
2505         (defined($dep->{'Rel'}) and !version_compare( $pkgs->{$pkgname}{'Version'}, $dep->{'Rel'}, $dep->{'Version'} ) ) ) {
2506         my %deplist;
2507         $deplist{$pkgname} = $dep;
2508         my $deps = build_deplist(\%deplist);
2509         $pkgs->{$pkgname}{'Unsatisfied'} = $deps if $savedep;
2510         return $deps;
2511     }
2512
2513     # set cache to "" to avoid infinite recursion
2514     $pkgs->{$pkgname}{'Unsatisfied'} = "" if $savedep;
2515
2516     if (defined $pkgs->{$dep->{'Package'}}{'Depends'}) {
2517         my $deps = parse_deplist( $pkgs->{$dep->{'Package'}}{'Depends'} );
2518         foreach (keys %$deps) {
2519             $dep = $$deps{$_};
2520             # recur on dep.
2521             my $ret = get_unsatisfied_dep($bd,$pkgs,$dep,1);
2522             if ($ret ne "") {
2523                 my $retdep = parse_deplist( $ret );
2524                 foreach (keys %$retdep) {
2525                     $dep = $$retdep{$_};
2526
2527                     $dep->{'Rel'} = '>=' if defined($dep->{'Rel'}) and $dep->{'Rel'} =~ '^=';
2528
2529                     if (defined($dep->{'Rel'}) and $dep->{'Rel'} =~ '^>' and defined ($pkgs->{$dep->{'Package'}}) and
2530                         version_compare($bd->{$pkgs->{$dep->{'Package'}}{'Source'}}{'ver'},'>>',$pkgs->{$dep->{'Package'}}{'Sourcev'})) {
2531                         if (not defined($merge_binsrc{$dep->{'Package'}})) {
2532                             # the uninstallable package doesn't exist in the new source; look for something else that does.
2533                             delete $$retdep{$dep->{'Package'}};
2534                             foreach (sort (split( /\s*,\s*/, $bd->{$pkgs->{$dep->{'Package'}}{'Source'}}{'bin'}))) {
2535                                 next if ($pkgs->{$_}{'all'} or not defined $pkgs->{$_}{'Version'});
2536                                 $dep->{'Package'} = $_;
2537                                 $dep->{'Rel'} = '>>';
2538                                 $dep->{'Version'} = $pkgs->{$_}{'Version'};
2539                                 $$retdep{$_} = $dep;
2540                                 last;
2541                             }
2542                         }
2543                     } else {
2544                         # sanity check to make sure the depending binary still exists, and the depended binary exists and dep-wait on a new version of it
2545                         if ( defined($merge_binsrc{$pkgname}) and defined($pkgs->{$dep->{'Package'}}{'Version'}) ) {
2546                             delete $$retdep{$dep->{'Package'}};
2547                             $dep->{'Package'} = $pkgname;
2548                             $dep->{'Rel'} = '>>';
2549                             $dep->{'Version'} = $pkgs->{$pkgname}{'Version'};
2550                             $$retdep{$pkgname} = $dep;
2551                         }
2552                         delete $$retdep{$dep->{'Package'}} if (defined ($dep->{'Rel'}) and $dep->{'Rel'} =~ '^>');
2553                     }
2554                 }
2555                 $ret = build_deplist($retdep);
2556                 $pkgs->{$pkgname}{'Unsatisfied'} = $ret if $savedep;
2557                 return $ret;
2558             }
2559         }
2560     }
2561     return "";
2562 }
2563
2564 sub call_edos_depcheck {
2565     my $packagesfile = shift;
2566     my $sourcesfile = shift;
2567     my $key;
2568     
2569     return if defined ($conf::distributions{$distribution}{noadw});
2570
2571     # We need to check all of needs-build, as any new upload could make
2572     # something in needs-build have uninstallable deps
2573     # We also check everything in bd-uninstallable, as any new upload could
2574     # make that work again
2575     my %interesting_packages;
2576     foreach $key (keys %db) {
2577         my $pkg = $db{$key};
2578         if (defined $pkg and isin($pkg->{'State'}, qw/Needs-Build BD-Uninstallable/)) {
2579                 $interesting_packages{$key} = undef;
2580         }
2581     }
2582     
2583     #print "I would look at these sources with edos-depcheck:\n";
2584     #print join " ", keys %interesting_packages,"\n";
2585
2586     if (open(EDOS,"-|","wb-edos-builddebcheck", "-a", $arch, $packagesfile, $sourcesfile)) {
2587         local($/) = ""; # read in paragraph mode
2588         while( <EDOS> ) {
2589                 my( $key, $reason ) ;
2590                 s/\s*$//m;
2591                 /^Package:\s*(\S+)$/mi and $key = $1;
2592                 /^Failed-Why:(([^\n]|\n ([^\n]|\.))*)$/msi and $reason = $1;
2593                 $reason =~ s/^\s*//mg;
2594                 $reason ||= 'No reason given by edos-debcheck';
2595
2596                 if (exists $interesting_packages{$key}) {
2597                     $interesting_packages{$key} = $reason;
2598                 } else {
2599                     print "TODO: edos reported a package we do not care about now" if $verbose;
2600                 }
2601         }
2602         close EDOS;
2603     } else {
2604         print "ERROR: Could not run wb-edos-builddebcheck. I am continuing, assuming\n" .
2605               "all packages have installable build-dependencies."
2606     }
2607
2608     for my $key (keys %interesting_packages) {
2609         my $pkg = $db{$key};
2610         my $change = 
2611             (defined $interesting_packages{$key} and $pkg->{'State'} eq 'Needs-Build') ||
2612             (not defined $interesting_packages{$key} and $pkg->{'State'} eq 'BD-Uninstallable');
2613         if ($change) {
2614             if (defined $interesting_packages{$key}) {
2615                     change_state( \$pkg, 'BD-Uninstallable' );
2616                     $pkg->{'Reason'} = $interesting_packages{$key};
2617             } else {
2618                     change_state( \$pkg, 'Needs-Build' );
2619             }
2620             log_ta( $pkg, "--merge-all" );
2621             $db{$key} = $pkg;
2622             print "edos-builddebchange changed state of ${key}_$pkg->{'Version'} to $pkg->{'State'}\n" if $verbose;
2623         }
2624     }
2625 }
2626
2627 sub usage {
2628         my $prgname;
2629         ($prgname = $0) =~ s,^.*/,,;
2630         print <<"EOF";
2631 Usage: $prgname <options...> <package_version...>
2632 Options:
2633     -v, --verbose: Verbose execution.
2634     --take: Take package for building [default operation]
2635     -f, --failed: Record in database that a build failed due to
2636         deficiencies in the package (that aren't fixable without a new
2637         source version).
2638     -u, --uploaded: Record in the database that the packages build
2639         correctly and were uploaded.
2640     -n, --no-build: Record in the database that the packages aren't
2641         desired for this architecture and shouldn't appear in listings even
2642         if they're out of date.
2643     --dep-wait: Record in the database that the packages are waiting
2644         for some source dependencies to become available
2645     --binNMU num: Schedule a re-build of the package with unchanged source, but
2646          a new version number (source-version + "+b<num>")
2647     --give-back: Mark a package as ready to build that is in state Building,
2648          Built or Build-Attempted. To give back a package in state Failed, use
2649          --override
2650     --merge-quinn: Merge quinn-diff output into database.
2651     --merge-packages: Merge Packages files into database.
2652     --pretend-avail: Pretend that given packages are available now and give
2653         free packages waiting for them
2654     -i SRC_PKG, --info SRC_PKG: Show information for source package
2655     -l STATE, --list=STATE: List all packages in state STATE; can be
2656         combined with -U to restrict to a specific user; STATE can
2657         also be 'all'
2658     -m MESSAGE, --message=MESSAGE: Give reason why package failed or
2659         source dependency list
2660         (used with -f, --dep-wait, and --binNMU)
2661     -o, --override: Override another user's lock on a package, i.e.
2662         take it over; a notice mail will be sent to the other user
2663     -U USER, --user=USER: select user name for which listings should
2664         apply, if not given all users are listed.
2665         if -l is missing, set user name to be entered in db; usually
2666         automatically choosen
2667     --import FILE: Import database from a ASCII file FILE
2668     --export FILE: Export database to a ASCII file FILE
2669     --lock-for PID: Locks the database for the process with this pid
2670     --unlock-for PID: Unlocks the database for the process with this pid
2671     --act-on-behalf-of PID: Ignores the log (if it is held by this pid)
2672     --start-transaction: Creates a copy of the state of the database, for
2673         use with --transactional. This overrides any previous uncommited
2674         transaction. Should only be used after --lock-for
2675     --commit-transaction: Atomically moves the copy back to the main, thus
2676         commiting the changes
2677     --transactional: Flag to indicate that we want to work on the copy
2678
2679 The remaining arguments (depending on operation) usually start with
2680 "name_version", the trailer is ignored. This allows to pass the names
2681 of .dsc files, for which file name completion can be used.
2682 --merge-packages and --merge-quinn take Package/quin--diff file names
2683 on the command line or read stdin. --list needs nothing more on the
2684 command line. --info takes source package names (without version).
2685 EOF
2686         exit 1;
2687 }
2688
2689 sub pkg_version_eq {
2690         my $pkg = shift;
2691         my $version = shift;
2692
2693         return 1
2694                if (defined $pkg->{'Binary-NMU-Version'}) and 
2695                version_compare(binNMU_version($pkg->{'Version'},
2696                         $pkg->{'Binary-NMU-Version'}),'=', $version);
2697         return version_compare( $pkg->{'Version'}, "=", $version );
2698 }