#!/usr/bin/perl

# Basically a speciallized grep

require "getopts.pl";

$zgrep = "zgrep -l";
$grep = "grep -l";

$nocase = "-i";

$default_d = "/usr/doc:/usr/local/doc";
$default_i = "/usr/info:/usr/local/info";
$default_m = "/usr/man:/usr/X11/man:/usr/local/man";

$opt_d = $default_d;
$opt_i = $default_i;
$opt_m = $default_m;
$opt_n = 0;

# If this is not "", it is a colon separated list
# of man page sections to limit the search to
$opt_c = "";

&Getopts('d:i:m:c:n');

# Run $command, prefix stdout with $prefix
# Discard all stderr
sub prefix_out {
    local ( $prefix, $command ) = @_;

    open(SAVEERR, ">&STDERR");
    open(STDERR, ">/dev/null");

    open(FD, "$command |");
    while (<FD>) {
	print "$prefix: $_";
    }

    open(STDERR, ">&SAVEERR");
}

if (! $ARGV[0]) {
    print
<<EOM
usage: helpme [-d <docpath>] [-i <infopath>] [-n]\
              [-m <manpath>] [-c <manextpath>] pattern
       Paths are colon separated.
       The man extension path is extensions only!
       Defaults:
           docpath  = $default_d
           infopath = $default_i
           manpath  = $default_m
           manext   = search all by deafult
EOM
    ;
    exit(1);
}

$pattern = $ARGV[0];

if ($opt_n) {
    $grep = "$grep $nocase";
    $zgrep = "$zgrep $nocase";
}

## Search doc files

foreach $d (split(':', $opt_d)) {
    opendir(D, "$d");
    @files = ();
    while ($_ = readdir(D)) {
	push(@files,("$d/$_")) if -f "$d/$_";
    }
    close(D);
    if (scalar(@files)) {
	&prefix_out("doc", "$zgrep $pattern @files");
    }
}

## Search info files

foreach $d (split(':', $opt_i)) {
    opendir(D, "$d");
    @files = ();
    while ($_ = readdir(D)) {
	push(@files,("$d/$_")) if -f "$d/$_";
    }
    close(D);
    if (scalar(@files)) {
	&prefix_out("info", "$zgrep $pattern @files");
    }
}

## Search man pages

if ($opt_c ne "") {
    @mansec = split(':', $opt_c);
}

foreach $d (split(':', $opt_m)) {
    opendir(D, "$d");
    @mandirs = ();
    while ($_ = readdir(D)) {
	if (-d "$d/$_") {
	    push(@mandirs,("$d/$_")) if /^man/;
	}
    }
  DIR:
    foreach $_ (@mandirs) {
	if ($opt_c eq "") {
	    &prefix_out("man", "$grep $pattern $_/*");
	} else {
	    foreach $s (@mansec) {
		if (/$s$/) {
		    &prefix_out("man", "$grep $pattern $_/*");
		    next DIR;
		}
	    }
	}
    }
}

