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