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