#!/usr/bin/env perl6
use v6;
use File::Find;
use MONKEY-SEE-NO-EVAL; # until we have a better serialisation

# 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() {
    my $me = 'p6doc-index';

    say "Usage: $me build        to build an index for 'p6doc -f'";
    say "Usage: $me list         to list the names";
    say "Usage: $me lookup <key> to display module name containing key";
    say "Usage: $me path-to-index to show where the index file lives";
}

multi sub MAIN('path-to-index') {
    say INDEX if INDEX.IO.e;
}

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

    # XXX should index more than this - currently only core pod
    for ($*REPO.repo-chain()>>.Str X~ "{$*SPEC.dir-sep}doc{$*SPEC.dir-sep}").grep: *.IO.d  -> $lib_path is copy {
        my @files =  find(:dir($lib_path),:type('file')).map({.IO});

        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(/"{$*SPEC.dir-sep}"/,'::',:g);
            my $section = '';
            for open( $file.Str).lines -> $row {
                if $row ~~ /^\=(item|head\d) \s+ (.*?) \s*$/ {
                    $section = $1.Str if $1.defined;
                    %words{$section}.push([$pod, $section]);
                }
                if $row ~~ /X\<(.*?)\>/ and $section {
                    my $x = $0.Str if $0.defined;
                    %words{$x}.push([$pod, $section]) if $x ~~ m/^<alpha>/;
                }
            }
        }
    }

    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;
    }
}

# vim: expandtab shiftwidth=4 ft=perl6
