#!/usr/bin/perl -w
# (C) 2003-2007 Willem Jan Hengeveld <itsme@xs4all.nl>
# Web: http://www.xs4all.nl/~itsme/
#      http://wiki.xda-developers.com/
#
# $Id$
#

use strict;

# I wrote this script before I discovered that cygwin grep also has a '-P'
# option.

use Wild;
use IO::File;
use Getopt::Long;

my $g_flagCaseInsensitive;
my $g_flagRecurseSubdirectories;

sub usage {
    return <<__EOF__
Usage: pgrep [options] pattern  files dirs ...
    -i    case insensitive
    -r    recurse into subdirs
__EOF__
}
GetOptions(
    "i" => \$g_flagCaseInsensitive,
    "r" => \$g_flagRecurseSubdirectories,
) or die usage();

my $g_pattern= shift;

for (@ARGV) {
    ProcessPath($_, 1);
}
exit(0);

sub ProcessFile
{
    my ($fn)= @_;
    my $fh= IO::File->new($fn, "r");

    my $modifiers= $g_flagCaseInsensitive ? "(?i)":"";

    while (<$fh>)
    {
        s/[\r\n]+$//;
        if (/$modifiers$g_pattern/)
        {
            print "$fn: $_\n";
        }
    }
    $fh->close();
}

sub ProcessDir {
    my ($path)= @_;

    opendir(DIR, $path) or warn "$!: reading $path\n";
    my @files= readdir DIR;
    closedir DIR;

    for (@files) {
        next if ($_ eq "." || $_ eq "..");
        my $fullpath= makeFullPath($path, $_);
        ProcessPath($fullpath, $g_flagRecurseSubdirectories);
    }
}
sub ProcessPath {
    my ($path, $doRecurse)= @_;
    if (-f $_) {
        ProcessFile($_);
    }
    elsif ($doRecurse && -d $_) {
        ProcessDir($_);
    }
}


sub makeFullPath {
    my ($full, @parts)= @_;

    $full ||="";
    for my $path (@parts) {
        next if (!defined $path);
        $path =~ s{^/}{};         # remove leading slash
        $full =~ s{/?$}{/$path};  # remove trailing slash, append path
    }

    return $full;
}

