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