#!/usr/bin/perl -- -*- Perl -*-

# In part from "Programming Perl," L. Wall & R. L. Schwartz, 1991

# Usage: rgrep pattern dir

$debugging = 0;

# Get pattern and protect the delimiter we'll use.

$pattern = shift;
$pattern =~ s/!/\\!/g;

# Get file

$start_file = shift || $ENV{'LINK_BASE'} || '.';

if (! $pattern) {
    die "Usage: $0 <pattern> [<file>|<directory>]\n";
}

if (! -e $start_file) {
    die "Usage: $0 No file $start\n";
}

$prog =<<EOF;
&search_through("$start_file");

sub search_through {

    local(\$file) = \@_[$[];

    if (-d \$file) {

	opendir(DIR,\$file) || die \$!;
	local(\@DIRfiles) = grep(!/^\\.\\.?\$/, readdir(DIR));
	closedir(DIR);

	foreach (\@DIRfiles) {
	    &search_through(\$file . "/" . \$_);
	}

    }
    elsif (-T \$file) {

	open(FILE,\$file) || die \$!;

	\$file =~ s!^$start_file/!!;

	\$found = 0;
	\$line = 0;
	while(<FILE>) {
	    \$line++;
	    if(m!$pattern!) {
		print('* ', \$file, "\\n"), \$found = 1 if ! \$found;
		print "  ", \$line, ":\\t", \$_;
	    }
	}
	close(FILE);

    }

}
EOF

print $prog if $debugging;

eval $prog;
die $@ if $@;

