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