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