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