#!/usr/bin/perl6-m
use v6;
use File::Find;

# XXX this script probably should be refactored into p6doc itself

sub findbin() returns Str {
    $*PROGRAM_NAME.subst(rx{<-[/\\]>+$}, '');
}

constant INDEX = findbin() ~ 'index.data';

multi sub MAIN() {
    say "Usage: $*PROGRAM_NAME build        to build an index for 'p6doc -f'";
    say "Usage: $*PROGRAM_NAME list         to list the names";
    say "Usage: $*PROGRAM_NAME lookup <key> to display module name containing key";
    say "Usage: $*PROGRAM_NAME path-to-index to show where the index file lives";
}

multi sub MAIN('path-to-index') {
    say INDEX;
}

multi sub MAIN('build') {
    my %words;

    # XXX p6doc probably uses another path to @*INC which is probably incomplete

    for ( @*INC ) -> $lib_path is copy {

        $lib_path = $lib_path.Str;
        my @files :=  find(:dir($lib_path),:type('file')); 

        for @files -> $f {
            my $file = $f.path;
            next if $file !~~ /\.pod$/;
            my $pod = substr($file.Str, 0 , $file.Str.chars -4);
            $pod.=subst(/$lib_path\//,"");
            $pod.=subst(/\//,'::',:g);
            my $section = '';
            for open( $file.Str).lines -> $row {
                if $row ~~ /^\=(item|head\d) \s+ (.*?) \s*$/ {
                    $section = $1.Str;
                    %words{$section}.push([$pod, $section]);
                }
                if $row ~~ /X\<(.*?)\>/ and $section {
                    my $x = $0.Str;
                    %words{$x}.push([$pod, $section]);
                }
            }
        }
    }

    my $out = open(INDEX, :w);
    $out.print(%words.perl);
    $out.close;
}

multi sub MAIN('list') {
    if INDEX.IO ~~ :e {
        my %data = EVAL slurp INDEX;
        for %data.keys.sort -> $name {
            say $name
        #    my $newdoc = %data{$docee}[0][0] ~ "." ~ %data{$docee}[0][1];
        #    return MAIN($newdoc, :f);
        }
    } else {
        say "First run   $*PROGRAM_NAME build    to create the index";
        exit;
    }
}

multi sub MAIN('lookup', $key) {
    if INDEX.IO ~~ :e {
        my %data = EVAL slurp INDEX;
        die "not found" unless %data{$key};
        say %data{$key}.split(" ").[0];
    } else {
        say "First run   $*PROGRAM_NAME build    to create the index";
        exit;
    }
}

