]> git.donarmstrong.com Git - infobot.git/blob - src/Modules/Debian.pl
regex support for 'query' in &searchDesc()
[infobot.git] / src / Modules / Debian.pl
1 #
2 #   Debian.pl: Frontend to debian contents and packages files
3 #      Author: dms
4 #     Version: v0.8 (20000918)
5 #     Created: 20000106
6 #
7
8 package Debian;
9
10 use strict;
11
12 # format: "alias=real".
13 my $announce    = 0;
14 my $defaultdist = "unstable";
15 my $refresh = &::getChanConfDefault("debianRefreshInterval",
16                         undef, 7) * 60 * 60 * 24;
17
18 my %dists       = (
19         "unstable"      => "sid",
20         "testing"       => "woody",     # new since 20001219.
21         "stable"        => "potato",
22         "incoming"      => "incoming",
23 ### the following don't work. too much effort to get 3 types of distros
24 ### to work harmoniously :-)
25         "slink"         => "archive-2.1",
26         "hamm"          => "archive-2.0",
27         "rex"           => "archive-1.?",
28         "bo"            => "archive-1.?",
29 );
30
31 my %urlcontents = (
32         "debian/Contents-##DIST-i386.gz" =>
33                 "ftp://ftp.us.debian.org".
34                 "/debian/dists/##DIST/Contents-i386.gz",
35 ### APPEARS TO BE FIXED?
36 # => strip control chars just to be safe.
37         "debian/Contents-##DIST-i386-non-US.gz" =>
38                 "ftp://non-us.debian.org".
39                 "/debian-non-US/dists/##DIST/non-US/Contents-i386.gz",
40 );
41
42 my %urlpackages = (
43         "debian/Packages-##DIST-main-i386.gz" =>
44                 "ftp://ftp.us.debian.org".
45                 "/debian/dists/##DIST/main/binary-i386/Packages.gz",
46         "debian/Packages-##DIST-contrib-i386.gz" =>
47                 "ftp://ftp.us.debian.org".
48                 "/debian/dists/##DIST/contrib/binary-i386/Packages.gz",
49         "debian/Packages-##DIST-non-free-i386.gz" =>
50                 "ftp://ftp.us.debian.org".
51                 "/debian/dists/##DIST/non-free/binary-i386/Packages.gz",
52
53         "debian/Packages-##DIST-non-US-main-i386.gz" =>
54                 "ftp://non-us.debian.org".
55                 "/debian-non-US/dists/##DIST/non-US/main/binary-i386/Packages.gz",
56         "debian/Packages-##DIST-non-US-contrib-i386.gz" =>
57                 "ftp://non-us.debian.org".
58                 "/debian-non-US/dists/##DIST/non-US/contrib/binary-i386/Packages.gz",
59         "debian/Packages-##DIST-non-US-non-free-i386.gz" =>
60                 "ftp://non-us.debian.org".
61                 "/debian-non-US/dists/##DIST/non-US/non-free/binary-i386/Packages.gz",
62 );
63
64 #####################
65 ### COMMON FUNCTION....
66 #######################
67
68 ####
69 # Usage: &DebianDownload(%hash);
70 sub DebianDownload {
71     my ($dist, %urls)   = @_;
72     my $bad     = 0;
73     my $good    = 0;
74
75     if (! -d "debian/") {
76         &::status("Debian: creating debian dir.");
77         mkdir("debian/",0755);
78     }
79
80     # fe dists.
81     # Download the files.
82     my $file;
83 ##    my %ret;
84     foreach $file (keys %urls) {
85         my $url = $urls{$file};
86         $url  =~ s/##DIST/$dist/g;
87         $file =~ s/##DIST/$dist/g;
88         my $update = 0;
89
90         if ( -f $file) {
91             my $last_refresh = (stat($file))[9];
92             $update++ if (time() - $last_refresh > $refresh);
93         } else {
94             $update++;
95         }
96
97         next unless ($update);
98
99         &::DEBUG("announce == $announce.");
100         if ($good + $bad == 0 and !$announce) {
101             &::status("Debian: Downloading files for '$dist'.");
102             &::msg($::who, "Updating debian files... please wait.");
103             $announce++;
104         }
105
106         if (exists $::debian{$url}) {
107             &::DEBUG("2: ".(time - $::debian{$url})." <= $refresh");
108             next if (time() - $::debian{$url} <= $refresh);
109             &::DEBUG("stale for url $url; updating!");
110         }
111
112         if ($url =~ /^ftp:\/\/(.*?)\/(\S+)\/(\S+)$/) {
113             my ($host,$path,$thisfile) = ($1,$2,$3);
114
115             # error internally to ftp.
116             # hope it doesn't do anything bad.
117             if ($file =~ /Contents-woody-i386-non-US/) {
118                 &::DEBUG("Skipping Contents-woody-i386-non-US.");
119 #               $file =~ s/woody/potato/;
120 #               $path =~ s/woody/potato/;
121 ###             next;
122             }
123
124             if (!&::ftpGet($host,$path,$thisfile,$file)) {
125                 &::WARN("deb: down: $file == BAD.");
126                 $bad++;
127                 next;
128             }
129
130             if (! -f $file) {
131                 &::DEBUG("deb: down: ftpGet: !file");
132                 $bad++;
133                 next;
134             }
135
136             if ($file =~ /Contents-potato-i386-non-US/) {
137                 &::DEBUG("hack: using potato's non-US contents for woody.");
138                 system("cp debian/Contents-potato-i386-non-US.gz debian/Contents-woody-i386-non-US.gz");
139             }
140
141             &::DEBUG("deb: download: good.");
142 ##          $ret{$
143             $good++;
144         } else {
145             &::ERROR("Debian: invalid format of url => ($url).");
146             $bad++;
147             next;
148         }
149     }
150
151     if ($good) {
152         &generateIndex($dist);
153         return 1;
154     } else {
155         return -1 unless ($bad);        # no download.
156         &::DEBUG("DD: !good and bad($bad). :(");
157         return 0;
158     }
159 }
160
161 ###########################
162 # DEBIAN CONTENTS SEARCH FUNCTIONS.
163 ########
164
165 ####
166 # Usage: &searchContents($query);
167 sub searchContents {
168     my ($dist, $query)  = &getDistroFromStr($_[0]);
169     &::status("Debian: Contents search for '$query' on $dist.");
170     my $dccsend = 0;
171
172     $dccsend++          if ($query =~ s/^dcc\s+//i);
173     ### larne's regex.
174     # $query = $query.'(\.so\.)?([.[[:digit:]]+\.]+)?$';
175
176     $query =~ s/\\([\^\$])/$1/g;        # hrm?
177     $query =~ s/^\s+|\s+$//g;
178
179     if (!&::validExec($query)) {
180         &::msg($::who, "search string looks fuzzy.");
181         return;
182     }
183
184     if ($dist eq "incoming") {          # nothing yet.
185         &::DEBUG("sC: dist = 'incoming'. no contents yet.");
186         return;
187     } else {
188         my %urls = &fixDist($dist, %urlcontents);
189         # download contents file.
190         &::DEBUG("deb: download 1.");
191         if (!&DebianDownload($dist, %urls)) {
192             &::WARN("Debian: could not download files.");
193         }
194     }
195
196     # start of search.
197     my $start_time = &::timeget();
198
199     my $found = 0;
200     my %contents;
201     my $grepRE;
202     my $front = 0;
203     ### TODO: search properly if /usr/bin/blah is done.
204     if ($query =~ s/\$$//) {
205         &::DEBUG("search-regex found.");
206         $grepRE = "$query\[ \t]";
207     } elsif ($query =~ s/^\^//) {
208         &::DEBUG("front marker regex found.");
209         $front = 1;
210         $grepRE = $query;
211     } else {
212         $grepRE = "$query*\[ \t]";
213     }
214
215     ### fix up grepRE for "*".
216     $grepRE =~ s/\*/.*/g;
217
218     my @files;
219     foreach (keys %urlcontents) {
220         s/##DIST/$dist/g;
221
222         next unless ( -f $_);
223         push(@files,$_);
224     }
225
226     if (!scalar @files) {
227         &::ERROR("sC: no files?");
228         &::msg($::who, "failed.");
229         return;
230     }
231
232     my $files = join(' ', @files);
233
234     open(IN,"zegrep -h '$grepRE' $files |");
235     while (<IN>) {
236         if (/^\.?\/?(.*?)[\t\s]+(\S+)\n$/) {
237             my ($file,$package) = ("/".$1,$2);
238             if ($query =~ /\//) {
239                 next unless ($file =~ /\Q$query\E/);
240             } else {
241                 my ($basename) = $file =~ /^.*\/(.*)$/;
242                 next unless ($basename =~ /\Q$query\E/);
243             }
244             next if ($query !~ /\.\d\.gz/ and $file =~ /\/man\//);
245             next if ($front and $file !~ /^\/\Q$query\E/);
246
247             $contents{$package}{$file} = 1;
248             $found++;
249         }
250
251         last if ($found > 100);
252     }
253     close IN;
254
255     my $pkg;
256
257     ### send results with dcc.
258     if ($dccsend) {
259         if (exists $::dcc{'SEND'}{$::who}) {
260             &::msg($::who, "DCC already active!");
261             return;
262         }
263
264         if (!scalar %contents) {
265             &::msg($::who,"search returned no results.");
266             return;
267         }
268
269         my $file = "$::param{tempDir}/$::who.txt";
270         if (!open(OUT,">$file")) {
271             &::ERROR("Debian: cannot write file for dcc send.");
272             return;
273         }
274
275         foreach $pkg (keys %contents) {
276             foreach (keys %{$contents{$pkg}}) {
277                 # TODO: correct padding.
278                 print OUT "$_\t\t\t$pkg\n";
279             }
280         }
281         close OUT;
282
283         &::shmWrite($::shm, "DCC SEND $::who $file");
284
285         return;
286     }
287
288     &::status("Debian: $found contents results found.");
289
290     my @list;
291     foreach $pkg (keys %contents) {
292         my @tmplist = &::fixFileList(keys %{$contents{$pkg}});
293         my @sublist = sort { length $a <=> length $b } @tmplist;
294
295         pop @sublist while (scalar @sublist > 3);
296
297         $pkg =~ s/\,/\037\,\037/g;      # underline ','.
298         push(@list, "(". join(', ',@sublist) .") in $pkg");
299     }
300     # sort the total list from shortest to longest...
301     @list = sort { length $a <=> length $b } @list;
302
303     # show how long it took.
304     my $delta_time = &::timedelta($start_time);
305     &::status(sprintf("Debian: %.02f sec to complete query.", $delta_time)) if ($delta_time > 0);
306
307     my $prefix = "Debian Search of '$query' ";
308     if (scalar @list) { # @list.
309         &::pSReply( &::formListReply(0, $prefix, @list) );
310     } else {            # !@list.
311         &::DEBUG("ok, !\@list, searching desc for '$query'.");
312         &searchDesc($query);
313     }
314 }
315
316 ####
317 # Usage: &searchAuthor($query);
318 sub searchAuthor {
319     my ($dist, $query)  = &getDistroFromStr($_[0]);
320     &::DEBUG("searchAuthor: dist => '$dist', query => '$query'.");
321     $query =~ s/^\s+|\s+$//g;
322
323     # start of search.
324     my $start_time = &::timeget();
325     &::status("Debian: starting author search.");
326
327     my $files;
328     my ($bad,$good) = (0,0);
329     my %urls = %urlpackages;
330
331     foreach (keys %urlpackages) {
332         s/##DIST/$dist/g;
333
334         if (! -f $_) {
335             $bad++;
336             next;
337         }
338
339         $good++;
340         $files .= " ".$_;
341     }
342
343     &::DEBUG("good = $good, bad = $bad...");
344
345     if ($good == 0 and $bad != 0) {
346         my %urls = &fixDist($dist, %urlpackages);
347         &::DEBUG("deb: download 2.");
348         if (!&DebianDownload($dist, %urls)) {
349             &::ERROR("Debian(sA): could not download files.");
350             return;
351         }
352     }
353
354     my (%maint, %pkg, $package);
355     open(IN,"zegrep -h '^Package|^Maintainer' $files |");
356     while (<IN>) {
357         if (/^Package: (\S+)$/) {
358             $package = $1;
359         } elsif (/^Maintainer: (.*) \<(\S+)\>$/) {
360             my($name,$email) = ($1,$2);
361             if ($package eq "") {
362                 &::DEBUG("sA: package == NULL.");
363                 next;
364             }
365             $maint{$name}{$email} = 1;
366             $pkg{$name}{$package} = 1;
367             $package = "";
368         } else {
369             &::WARN("invalid line: '$_'.");
370         }
371     }
372     close IN;
373
374     my %hash;
375     # TODO: can we use 'map' here?
376     foreach (grep /\Q$query\E/i, keys %maint) {
377         $hash{$_} = 1;
378     }
379
380     # TODO: should we only search email if '@' is used?
381     if (scalar keys %hash < 15) {
382         my $name;
383         foreach $name (keys %maint) {
384             my $email;
385             foreach $email (keys %{$maint{$name}}) {
386                 next unless ($email =~ /\Q$query\E/i);
387                 next if (exists $hash{$name});
388                 $hash{$name} = 1;
389             }
390         }
391     }
392
393     my @list = keys %hash;
394     if (scalar @list != 1) {
395         my $prefix = "Debian Author Search of '$query' ";
396         &::pSReply( &::formListReply(0, $prefix, @list) );
397         return 1;
398     }
399
400     &::DEBUG("showing all packages by '$list[0]'...");
401
402     my @pkg = sort keys %{$pkg{$list[0]}};
403
404     # show how long it took.
405     my $delta_time = &::timedelta($start_time);
406     &::status(sprintf("Debian: %.02f sec to complete query.", $delta_time)) if ($delta_time > 0);
407
408     my $email   = join(', ', keys %{$maint{$list[0]}});
409     my $prefix  = "Debian Packages by $list[0] \002<\002$email\002>\002 ";
410     &::pSReply( &::formListReply(0, $prefix, @pkg) );
411 }
412
413 ####
414 # Usage: &searchDesc($query);
415 sub searchDesc {
416     my ($dist, $query)  = &getDistroFromStr($_[0]);
417     &::DEBUG("searchDesc: dist => '$dist', query => '$query'.");
418     $query =~ s/^\s+|\s+$//g;
419
420     # start of search.
421     my $start_time = &::timeget();
422     &::status("Debian: starting desc search.");
423
424     my $files;
425     my ($bad,$good) = (0,0);
426     my %urls = %urlpackages;
427
428     foreach (keys %urlpackages) {
429         s/##DIST/$dist/g;
430
431         if (! -f $_) {
432             $bad++;
433             next;
434         }
435
436         $good++;
437         $files .= " ".$_;
438     }
439
440     &::DEBUG("good = $good, bad = $bad...");
441
442     if ($good == 0 and $bad != 0) {
443         my %urls = &fixDist($dist, %urlpackages);
444         &::DEBUG("deb: download 2c.");
445         if (!&DebianDownload($dist, %urls)) {
446             &::ERROR("Debian(sD): could not download files.");
447             return;
448         }
449     }
450
451     my (%desc, $package);
452     open(IN,"zegrep -h '^Package|^Description' $files |");
453     $query =~ s/\*/\\S*/g;      # regex.
454     while (<IN>) {
455         if (/^Package: (\S+)$/) {
456             $package = $1;
457         } elsif (/^Description: (.*)$/) {
458             my $desc = $1;
459             next unless ($desc =~ /\Q$query\E/i);
460             if ($package eq "") {
461                 &::WARN("sD: package == NULL?");
462                 next;
463             }
464             $desc{$package} = $desc;
465             $package = "";
466         } else {
467             &::WARN("invalid line: '$_'.");
468         }
469     }
470     close IN;
471
472     my @list = keys %desc;
473     if (!scalar @list) {
474         my $prefix = "Debian Desc Search of '$query' ";
475         &::pSReply( &::formListReply(0, $prefix, ) );
476     } elsif (scalar @list == 1) {       # list = 1.
477         &::DEBUG("list == 1; showing package info of '$list[0]'.");
478         &infoPackages("info", $list[0]);
479     } else {                            # list > 1.
480         my $prefix = "Debian Desc Search of '$query' ";
481         &::pSReply( &::formListReply(0, $prefix, @list) );
482     }
483
484     # show how long it took.
485     my $delta_time = &::timedelta($start_time);
486     &::status(sprintf("Debian: %.02f sec to complete query.", $delta_time)) if ($delta_time > 0);
487 }
488
489 ####
490 # Usage: &generateIncoming();
491 sub generateIncoming {
492     my $pkgfile  = "debian/Packages-incoming";
493     my $idxfile  = $pkgfile.".idx";
494     my $stale    = 0;
495     $stale++ if (&::isStale($pkgfile.".gz", $refresh));
496     $stale++ if (&::isStale($idxfile, $refresh));
497     &::DEBUG("gI: stale => '$stale'.");
498     return 0 unless ($stale);
499
500     ### STATIC URL.
501     my %ftp = &::ftpList("llug.sep.bnl.gov", "/pub/debian/Incoming/");
502
503     if (!open(PKG,">$pkgfile")) {
504         &::ERROR("cannot write to pkg $pkgfile.");
505         return 0;
506     }
507     if (!open(IDX,">$idxfile")) {
508         &::ERROR("cannot write to idx $idxfile.");
509         return 0;
510     }
511
512     print IDX "*$pkgfile.gz\n";
513     my $file;
514     foreach $file (sort keys %ftp) {
515         next unless ($file =~ /deb$/);
516
517         if ($file =~ /^(\S+)\_(\S+)\_(\S+)\.deb$/) {
518             print IDX "$1\n";
519             print PKG "Package: $1\n";
520             print PKG "Version: $2\n";
521             print PKG "Architecture: ", (defined $4) ? $4 : "all", "\n";
522         }
523         print PKG "Filename: $file\n";
524         print PKG "Size: $ftp{$file}\n";
525         print PKG "\n";
526     }
527     close IDX;
528     close PKG;
529
530     system("gzip -9fv $pkgfile");       # lame fix.
531
532     &::status("Debian: generateIncoming() complete.");
533 }
534
535
536 ##############################
537 # DEBIAN PACKAGE INFO FUNCTIONS.
538 #########
539
540 # Usage: &getPackageInfo($query,$file);
541 sub getPackageInfo {
542     my ($package, $file) = @_;
543
544     if (! -f $file) {
545         &::status("gPI: file $file does not exist?");
546         return 'NULL';
547     }
548
549     my $found = 0;
550     my (%pkg, $pkg);
551
552     open(IN, "zcat $file 2>&1 |");
553
554     my $done = 0;
555     while (!eof IN) {
556         $_ = <IN>;
557
558         next if (/^ \S+/);      # package long description.
559
560         # package line.
561         if (/^Package: (.*)\n$/) {
562             $pkg = $1;
563             if ($pkg =~ /^$package$/i) {
564                 $found++;       # we can use pkg{'package'} instead.
565                 $pkg{'package'} = $pkg;
566             }
567
568             next;
569         }
570
571         if ($found) {
572             chop;
573
574             if (/^Version: (.*)$/) {
575                 $pkg{'version'}         = $1;
576             } elsif (/^Priority: (.*)$/) {
577                 $pkg{'priority'}        = $1;
578             } elsif (/^Section: (.*)$/) {
579                 $pkg{'section'}         = $1;
580             } elsif (/^Size: (.*)$/) {
581                 $pkg{'size'}            = $1;
582             } elsif (/^Installed-Size: (.*)$/i) {
583                 $pkg{'installed'}       = $1;
584             } elsif (/^Description: (.*)$/) {
585                 $pkg{'desc'}            = $1;
586             } elsif (/^Filename: (.*)$/) {
587                 $pkg{'find'}            = $1;
588             } elsif (/^Pre-Depends: (.*)$/) {
589                 $pkg{'depends'}         = "pre-depends on $1";
590             } elsif (/^Depends: (.*)$/) {
591                 if (exists $pkg{'depends'}) {
592                     $pkg{'depends'} .= "; depends on $1";
593                 } else {
594                     $pkg{'depends'} = "depends on $1";
595                 }
596             } elsif (/^Maintainer: (.*)$/) {
597                 $pkg{'maint'} = $1;
598             } elsif (/^Provides: (.*)$/) {
599                 $pkg{'provides'} = $1;
600             } elsif (/^Suggests: (.*)$/) {
601                 $pkg{'suggests'} = $1;
602             } elsif (/^Conflicts: (.*)$/) {
603                 $pkg{'conflicts'} = $1;
604             }
605
606 ###         &::DEBUG("=> '$_'.");
607         }
608
609         # blank line.
610         if (/^$/) {
611             undef $pkg;
612             last if ($found);
613             next;
614         }
615
616         next if (defined $pkg);
617     }
618
619     close IN;
620
621     %pkg;
622 }
623
624 # Usage: &infoPackages($query,$package);
625 sub infoPackages {
626     my ($query,$dist,$package) = ($_[0], &getDistroFromStr($_[1]));
627
628     &::status("Debian: Searching for package '$package' in '$dist'.");
629
630     # download packages file.
631     # hrm...
632     my %urls = &fixDist($dist, %urlpackages);
633     if ($dist ne "incoming") {
634         &::DEBUG("deb: download 3.");
635         if (!&DebianDownload($dist, %urls)) {   # no good download.
636             &::WARN("Debian(iP): could not download ANY files.");
637         }
638     }
639
640     # check if the package is valid.
641     my $incoming = 0;
642     my @files = &validPackage($package, $dist);
643     if (!scalar @files) {
644         &::status("Debian: no valid package found; checking incoming.");
645         @files = &validPackage($package, "incoming");
646         if (scalar @files) {
647             &::status("Debian: cool, it exists in incoming.");
648             $incoming++;
649         } else {
650             &::msg($::who, "Package '$package' does not exist.");
651             return 0;
652         }
653     }
654
655     if (scalar @files > 1) {
656         &::WARN("same package in more than one file; random.");
657         &::DEBUG("THIS SHOULD BE FIXED SOMEHOW!!!");
658         $files[0] = &::getRandom(@files);
659     }
660
661     if (! -f $files[0]) {
662         &::WARN("files[0] ($files[0]) doesn't exist.");
663         &::msg($::who, "WARNING: $files[0] does not exist? FIXME");
664         return 'NULL';
665     }
666
667     ### TODO: if specific package is requested, note down that a version
668     ###         exists in incoming.
669
670     my $found = 0;
671     my $file = $files[0];
672     my ($pkg);
673
674     ### TODO: use fe, dump to a hash. if only one version of the package
675     ###         exists. do as normal otherwise list all versions.
676     if (! -f $file) {
677         &::ERROR("D:iP: file '$file' DOES NOT EXIST!!! should never happen.");
678         return 0;
679     }
680     my %pkg = &getPackageInfo($package, $file);
681
682     # 'fm'-like output.
683     if ($query eq "info") {
684         if (scalar keys %pkg > 5) {
685             $pkg{'info'}  = "\002(\002". $pkg{'desc'} ."\002)\002";
686             $pkg{'info'} .= ", section ".$pkg{'section'};
687             $pkg{'info'} .= ", is ".$pkg{'priority'};
688             $pkg{'info'} .= ". Version: \002$pkg{'version'}\002";
689             $pkg{'info'} .= ", Packaged size: \002". int($pkg{'size'}/1024) ."\002 kB";
690             $pkg{'info'} .= ", Installed size: \002$pkg{'installed'}\002 kB";
691
692             if ($incoming) {
693                 &::status("iP: info requested and pkg is in incoming, too.");
694                 my %incpkg = &getPackageInfo($query, "debian/Packages-incoming");
695
696                 if (scalar keys %incpkg) {
697                    $pkg{'info'} .= ". Is in incoming ($incpkg{'file'}).";
698                 } else {
699                     &::ERROR("iP: pkg $query is in incoming but we couldn't get any info?");
700                 }
701             }
702         } else {
703             &::DEBUG("running debianCheck() due to problems (".scalar(keys %pkg).").");
704             &debianCheck();
705             &::DEBUG("end of debianCheck()");
706
707             &::msg($::who,"Debian: Package appears to exist but I could not retrieve info about it...");
708             return;
709         }
710     } 
711
712     if ($dist eq "incoming") {
713         $pkg{'info'} .= "Version: \002$pkg{'version'}\002";
714         $pkg{'info'} .= ", Packaged size: \002". int($pkg{'size'}/1024) ."\002 kB";
715         $pkg{'info'} .= ", is in incoming!!!";
716     }
717
718     if (!exists $pkg{$query}) {
719         if ($query eq "suggests") {
720             $pkg{$query} = "has no suggestions";
721         } elsif ($query eq "conflicts") {
722             $pkg{$query} = "does not conflict with any other package";
723         } elsif ($query eq "depends") {
724             $pkg{$query} = "does not depend on anything";
725         } elsif ($query eq "maint") {
726             $pkg{$query} = "has no maintainer";
727         } else {
728             $pkg{$query} = "has nothing about $query";
729         }
730     }
731
732     &::pSReply("$package: $pkg{$query}");
733 }
734
735 # Usage: &infoStats($dist);
736 sub infoStats {
737     my ($dist)  = @_;
738     $dist       = &getDistro($dist);
739     return unless (defined $dist);
740
741     &::DEBUG("infoS: dist => '$dist'.");
742
743     # download packages file if needed.
744     my %urls = &fixDist($dist, %urlpackages);
745     &::DEBUG("deb: download 4.");
746     if (!&DebianDownload($dist, %urls)) {
747         &::WARN("Debian(iS): could not download ANY files.");
748         &::msg($::who, "Debian(iS): internal error.");
749         return;
750     }
751
752     my %stats;
753     my %total;
754     my $file;
755     foreach $file (keys %urlpackages) {
756         $file =~ s/##DIST/$dist/g;      # won't work for incoming.
757         &::DEBUG("file => '$file'.");
758         if (exists $stats{$file}{'count'}) {
759             &::DEBUG("hrm... duplicate open with $file???");
760             next;
761         }
762
763         open(IN,"zcat $file 2>&1 |");
764
765         if (! -e $file) {
766             &::DEBUG("iS: $file does not exist.");
767             next;
768         }
769
770         while (!eof IN) {
771             $_ = <IN>;
772
773             next if (/^ \S+/);  # package long description.
774
775             if (/^Package: (.*)\n$/) {          # counter.
776                 $stats{$file}{'count'}++;
777                 $total{'count'}++;
778             } elsif (/^Maintainer: .* <(\S+)>$/) {
779                 $stats{$file}{'maint'}{$1}++;
780                 $total{'maint'}{$1}++;
781             } elsif (/^Size: (.*)$/) {          # compressed size.
782                 $stats{$file}{'csize'}  += $1;
783                 $total{'csize'}         += $1;
784             } elsif (/^i.*size: (.*)$/i) {      # installed size.
785                 $stats{$file}{'isize'}  += $1;
786                 $total{'isize'}         += $1;
787             }
788
789 ###         &::DEBUG("=> '$_'.");
790         }
791         close IN;
792     }
793
794     ### TODO: don't count ppl with multiple email addresses.
795
796     &::pSReply(
797         "Debian Distro Stats on $dist... ".
798         "\002$total{'count'}\002 packages, ".
799         "\002".scalar(keys %{$total{'maint'}})."\002 maintainers, ".
800         "\002". int($total{'isize'}/1024)."\002 MB installed size, ".
801         "\002". int($total{'csize'}/1024/1024)."\002 MB compressed size."
802     );
803
804 ### TODO: do individual stats? if so, we need _another_ arg.
805 #    foreach $file (keys %stats) {
806 #       foreach (keys %{$stats{$file}}) {
807 #           &::DEBUG("  '$file' '$_' '$stats{$file}{$_}'.");
808 #       }
809 #    }
810
811     return;
812 }
813
814
815
816 ###
817 # HELPER FUNCTIONS FOR INFOPACKAGES...
818 ###
819
820 # Usage: &generateIndex();
821 sub generateIndex {
822     my (@dists) = @_;
823     &::status("Debian: !!! generateIndex() called !!!");
824     if (!scalar @dists or $dists[0] eq '') {
825         &::ERROR("gI: no dists to generate index.");
826         return 1;
827     }
828
829     foreach (@dists) {
830         my $dist = &getDistro($_); # incase the alias is returned, possible?
831         my $idx  = "debian/Packages-$dist.idx";
832
833         # TODO: check if any of the Packages file have been updated then
834         #       regenerate it, even if it's not stale.
835         # TODO: also, regenerate the index if the packages file is newer
836         #       than the index.
837         next unless (&::isStale($idx, $::param{'debianRefreshInterval'}));
838         if (/^incoming$/i) {
839             &::DEBUG("gIndex: calling generateIncoming()!");
840             &generateIncoming();
841             next;
842         }
843
844         if (/^woody$/i) {
845             &::DEBUG("Copying old index of woody to -old");
846             system("cp $idx $idx-old");
847         }
848
849         &::DEBUG("gIndeX: calling DebianDownload($dist, ...).");
850         &DebianDownload($dist, %urlpackages);
851
852         &::status("Debian: generating index for '$dist'.");
853         if (!open(OUT,">$idx")) {
854             &::ERROR("cannot write to $idx.");
855             return 0;
856         }
857
858         my $packages;
859         foreach $packages (keys %urlpackages) {
860             $packages =~ s/##DIST/$dist/;
861
862             if (! -e $packages) {
863                 &::ERROR("gIndex: '$packages' does not exist?");
864                 next;
865             }
866
867             print OUT "*$packages\n";
868             open(IN,"zcat $packages |");
869
870             while (<IN>) {
871                 next unless (/^Package: (.*)\n$/);
872                 print OUT $1."\n";
873             }
874             close IN;
875         }
876         close OUT;
877     }
878
879     return 1;
880 }
881
882 # Usage: &validPackage($package, $dist);
883 sub validPackage {
884     my ($package,$dist) = @_;
885     my @files;
886     my $file;
887
888     &::DEBUG("D: validPackage($package, $dist) called.");
889
890     my $error = 0;
891     while (!open(IN, "debian/Packages-$dist.idx")) {
892         if ($error) {
893             &::ERROR("Packages-$dist.idx does not exist (#1).");
894             return;
895         }
896
897         &generateIndex($dist);
898
899         $error++;
900     }
901
902     my $count = 0;
903     while (<IN>) {
904         if (/^\*(.*)\n$/) {
905             $file = $1;
906             next;
907         }
908
909         if (/^\Q$package\E\n$/) {
910             push(@files,$file);
911         }
912         $count++;
913     }
914     close IN;
915
916     &::DEBUG("vP: scanned $count items in index.");
917
918     return @files;
919 }
920
921 sub searchPackage {
922     my ($dist, $query) = &getDistroFromStr($_[0]);
923     my $file = "debian/Packages-$dist.idx";
924     my @files;
925     my $error   = 0;
926     my $warn    = 0;
927
928     if ($query =~ tr/A-Z/a-z/) {
929         $warn++;
930     }
931
932     &::status("Debian: Search package matching '$query' in '$dist'.");
933     unlink $file if ( -z $file);
934
935     while (!open(IN, $file)) {
936         if ($dist eq "incoming") {
937             &::DEBUG("sP: dist == incoming; calling gI().");
938             &generateIncoming();
939         }
940
941         if ($error) {
942             &::ERROR("could not generate index!!!");
943             return;
944         }
945
946         $error++;
947         &::DEBUG("should we be doing this?");
948         &generateIndex(($dist));
949     }
950
951     while (<IN>) {
952         chop;
953
954         if (/^\*(.*)$/) {
955             $file = $1;
956
957             if (&::isStale($file, $::param{'debianRefreshInterval'})) {
958                 &::DEBUG("STALE $file! regen.");
959                 &generateIndex(($dist));
960 ###             @files = searchPackage("$query $dist");
961                 &::DEBUG("EVIL HACK HACK HACK.");
962                 last;
963             }
964
965             next;
966         }
967
968         if (/\Q$query\E/) {
969             push(@files,$_);
970         }
971     }
972     close IN;
973
974     if (scalar @files and $warn) {
975         &::msg($::who, "searching for package name should be fully lowercase!");
976     }
977
978     return @files;
979 }
980
981 sub getDistro {
982     my $dist = $_[0];
983
984     if (!defined $dist or $dist eq "") {
985         &::DEBUG("gD: dist == NULL; dist = defaultdist.");
986         $dist = $defaultdist;
987     }
988
989     if ($dist =~ /^(slink|hamm|rex|bo)$/i) {
990         &::DEBUG("Debian: deprecated version ($dist).");
991         &::msg($::who, "Debian: deprecated distribution version.");
992         return;
993     }
994
995     if (exists $dists{$dist}) {
996         return $dists{$dist};
997     } else {
998         if (!grep /^\Q$dist\E$/i, %dists) {
999             &::msg($::who, "invalid dist '$dist'.");
1000             return;
1001         }
1002
1003         return $dist;
1004     }
1005 }
1006
1007 sub getDistroFromStr {
1008     my ($str) = @_;
1009     my $dists   = join '|', %dists;
1010     my $dist    = $defaultdist;
1011
1012     if ($str =~ s/\s+($dists)$//i) {
1013         $dist = &getDistro(lc $1);
1014         $str =~ s/\\+$//;
1015     }
1016     $str =~ s/\\([\$\^])/$1/g;
1017
1018     return($dist,$str);
1019 }
1020
1021 sub fixDist {
1022     my ($dist, %urls) = @_;
1023     my %new;
1024     my ($key,$val);
1025
1026     while (($key,$val) = each %urls) {
1027         $key =~ s/##DIST/$dist/;
1028         $val =~ s/##DIST/$dist/;
1029         ### TODO: what should we do if the sar wasn't done.
1030         $new{$key} = $val;
1031     }
1032     return %new;
1033 }
1034
1035 sub DebianFind {
1036     ### H-H-H-HACK HACK HACK :)
1037     my ($str) = @_;
1038     my ($dist, $query) = &getDistroFromStr($str);
1039     my @results = sort &searchPackage($str);
1040
1041     if (!scalar @results) {
1042         &::Forker("debian", sub { &searchContents($str); } );
1043     } elsif (scalar @results == 1) {
1044         &::status("searchPackage returned one result; getting info of package instead!");
1045         &::Forker("debian", sub { &infoPackages("info", "$results[0] $dist"); } );
1046     } else {
1047         my $prefix = "Debian Package Listing of '$str' ";
1048         &::pSReply( &::formListReply(0, $prefix, @results) );
1049     }
1050 }
1051
1052 sub debianCheck {
1053     my $dir     = "debian/";
1054     my $error   = 0;
1055
1056     &::status("debianCheck() called.");
1057
1058     ### TODO: remove the following loop (check if dir exists before)
1059     while (1) {
1060         last if (opendir(DEBIAN, $dir));
1061         if ($error) {
1062             &::ERROR("dC: cannot opendir debian.");
1063             return;
1064         }
1065         mkdir $dir, 0755;
1066         $error++;
1067     }
1068
1069     my $retval = 0;
1070     my $file;
1071     while (defined($file = readdir DEBIAN)) {
1072         next unless ($file =~ /(gz|bz2)$/);
1073
1074         my $exit = system("gzip -t '$dir/$file'");
1075         next unless ($exit);
1076         &::DEBUG("hmr... => ".(time() - (stat($file))[8])."'.");
1077         next unless (time() - (stat($file))[8] > 3600);
1078
1079         &::DEBUG("dC: exit => '$exit'.");
1080         &::WARN("dC: '$dir/$file' corrupted? deleting!");
1081         unlink $dir."/".$file;
1082         $retval++;
1083     }
1084
1085     return $retval;
1086 }
1087
1088 1;