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