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