#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  FindMan - Search $MANPATH for a pattern
#
#SYNOPSIS
#  FindMan pat
#
#DESCRIPTION
#  Search all the files under all the directories in  $ENV{MANPATH}  for  the
#  pattern.   Note  that  it's  a perl pattern.  We don't run grep; we do the
#  matching in perl.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#  All ".*" files are ignored. There are no options to control this.  But man
#  directories really shouldn't have hidden man pages, should they?
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 1;	# Verbose level.

die "Usage: $P pattern\n" unless @ARGV;
$pat = shift;

@dirs = split(':',$ENV{'MANPATH'});
for $d (@dirs) {
	print "$P: dir \"$d\"\n" if $V>1;
	&onedir($d);
}

print "$P: Exit with status $exitstat.\n" if $V>1;
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
sub onedir {
	local($d) = @_;
	local($f,@files,$l,$path);
	unless (opendir(DIR,$d)) {
		print STDERR "$P: Can't read dir \"$d\"\n";
		return;
	}
	print "$P: Dir \"$d\"\n" if $V>1;
	@files = readdir(DIR);
	closedir(DIR);
file:
	for $f (@files) {
		next file if ($f =~ /^\./);
		if (-d ($path = "$d/$f")) {
			&onedir($path);
			next file;
		}
		unless (open(FIL,$path)) {
			print STDERR "$P: Can't read \"$path\"\n";
			next file;
		}
		while ($l = <FIL>) {
			print "$path:\t$l" if ($l =~ /$pat/i);
		}
		close FIL;
	}
}
