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