#!/usr/bin/perl
###########################################
# perldig
# Mike Schilli, 2003 (m@perlmeister.com)
###########################################
use warnings;
use strict;

use Config;
use SWISH::API;
use Shell::POSIX::Select;
use File::Basename;
use Getopt::Std;
use File::Path;
use File::Find::Rule;
use Pod::Simple::TextContent;

our $LESS  = "less";
our $SWISH = "swish-e";

our $IDX_FILE = 
           glob "~/.perldig/perldig.index";
our $CNF_FILE = 
           glob "~/.perldig/perldig.conf";

our @DIRS = ($Config{installsitearch},
             $Config{installsitelib},
             $Config{installarchlib},
             $Config{installprivlib},
            );

getopts("u", \my %opts);

if($opts{u}) {
    update_index();
} elsif(@ARGV) {
    search(@ARGV);
} else {
    stream_files();
}

###########################################
sub search {
###########################################
    my $term = join " ", @_;

    my $swish = SWISH::API->new($IDX_FILE);

    $swish->AbortLastError 
        if $swish->Error;

    my $results = $swish->Query(
                          join ' ', @ARGV);

    $swish->AbortLastError 
        if $swish->Error;

    my $hits = $results->Hits;
    if ( !$hits ) {
        print "No Results\n";
        return;
    }

    my @results = ();
    my @select  = ();
    my %map     = ();

    while (my $r = $results->NextResult) {
        push @results, $r;
        my $path = my $org_path =
             $r->Property( "swishdocpath");
        $path =~ s|^$_/|| for @DIRS;
        push @select, $path;
        $map{$path} = $org_path;
    }

    our($Eof, $Reply);

    select my $file (@select) {
        system "$LESS $map{$file}";
        last;
    }
}

###########################################
sub stream_files {
###########################################
    my $rule = File::Find::Rule
               ->file()
               ->name('*.pod', '*.pm')
               ->start(@DIRS);

    while(my $file = $rule->match()) {
        print STDERR "Processing $file\n";
        my $parser = 
           Pod::Simple::TextContent->new();
        my $output = "";
        $parser->output_string(\$output);
        $parser->parse_file($file);
        my $size = length($output);

        print "Path-Name: $file\n",
              "Document-Type: TXT*\n",
              "Content-Length: $size\n\n";
        print $output;
    }
}

############################################
sub update_index {
############################################
    if(! -e $CNF_FILE) {
        print "Creating $CNF_FILE\n";
        mkpath(dirname($CNF_FILE));
        open FILE, ">$CNF_FILE" or 
            die "Can't open $CNF_FILE ($!)";
        print FILE "IndexDir  $0\n",
                   "IndexFile $IDX_FILE\n",
                   "UseStemming Yes\n";
        close FILE;
    }
    system("$SWISH -c $CNF_FILE -S prog");
}
