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