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