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