#! /usr/bin/perl

use strict;
use warnings;
use File::Basename;
use File::Find ();
use File::ShareDir ();

our $VERSION = '0.01';

my $doc_dir = "doc";
eval {
    $doc_dir = File::ShareDir::dist_dir('cppref');
};

my $name = shift @ARGV || 'start';

$name =~ s{::}{/}g;
$name .= '/start'
    if -d "$doc_dir/$name";

# try by name
open_file("$doc_dir/$name.html")
    if -e "$doc_dir/$name.html";

my @cand;
my %cand_dir;
File::Find::find(
    {
        wanted => sub {
            my $fn = $_;
            return if $cand_dir{dirname($fn)};
            return unless $fn =~ m{/$name(?:\.|$)}i;
            push @cand, -d $fn ? "$fn/start.html" : $fn;
        },
        no_chdir => 1,
    },
    $doc_dir,
);
if (@cand == 0) {
    print STDERR "no document found for: $name\n";
    exit 1;
} elsif (@cand == 1) {
    open_file($cand[0]);
} else {
    print STDERR "multiple choices:\n";
    print map { s{$doc_dir/}{}; s{(/start|)\.html$}{}; s{/}{::}g; "  $_\n" } @cand;
    exit 2;
}

sub open_file {
    my $fn = shift;
    exec 'w3m', $fn;
    die "failed to exec w3m:$!";
}

__END__

=head1 NAME

cppref - man-style access to cppreference.com documents (using w3m)

=head1 SYNOPSIS

  % cppref        # prints top page
  % cppref vector # prints vector docs

=head1 AUTHOR

Copyright (c) 2009 Kazuho Oku  All rights reserved

=head1 LICENSE

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html

The documents are from http://www.cppreference.com/ (under Creative Commons Attribution 3.0 license).

=cut
