#!perl -w
# (C) 2003-2007 Willem Jan Hengeveld <itsme@xs4all.nl>
# Web: http://www.xs4all.nl/~itsme/
#      http://wiki.xda-developers.com/
#
# $Id: $
#
# this script searches in all files mentioned in CVS/Entries files
#
use strict;
use IO::File;
my %reproots;

$|=1;
my $pattern= shift;
if (@ARGV) {
    for my $dir (@ARGV) {
        ProcessDirectory($dir, $pattern);
    }
}
else {
    ProcessDirectory(".", $pattern);
}

printf("\ncvs repositories found from current dir:\n");
for my $rr (keys %reproots) {
    printf("%2d : %s\n", scalar @{$reproots{$rr}}, $rr);
}

sub ProcessCVSEntries {
    my ($path, $entriespath, $pattern)= @_;
    my $fh= IO::File->new($entriespath, "r");
    if ($fh) {
        while (<$fh>) {
            if (m{^(\w*)/([^/]+)/}) {
                my ($type, $name)= ($1, $2);
                my $fullpath="$path/$name";
                if ($type eq "D") {
                    printf("%s%s\n", $fullpath, -d $fullpath ? "/" : -f $fullpath ? "   **** EXPECTED DIRECTORY" : "   ****MISSING");
                }
                else {
                    printf("%s%s\n", $fullpath, -d $fullpath ? "/   **** EXPECTED FILE" : -f $fullpath ? "" : "   ****MISSING");
                    system "grep \"$pattern\" $fullpath" if (-f $fullpath);
                }
            }
        }
        $fh->close();
    }
    else {
        printf("no cvs in %s: $!\n", $entriespath);
    }
}
sub GetCVSRepository {
    my ($repositorypath)= @_;
    my $fh= IO::File->new($repositorypath, "r");
    if ($fh) {
        my $path= <$fh>;
        $fh->close();

        $path =~ s/\s+$//;
        return $path;
    }
    #printf("no cvs rep in %s: $!\n", $repositorypath);
    #return "";
}

sub process_rep {
    my ($path, $rep)= @_;

    my @path= split(/[\/\\]/, $path);
    my @rep= split(/[\/\\]/, $rep);
    my @common;

    while (@path && @rep
        && $path[-1] eq $rep[-1]) {
        push @common, pop @path;
        pop @rep;
    }
    my $pathroot=join("/", @path);
    my $reproot= join("/", @rep);
    my $common= join("/", @common);
    push @{$reproots{"${pathroot}::${reproot}"}}, $common;
}
sub ProcessDirectory {
    my ($path, $pattern)= @_;

    my $repository= GetCVSRepository("$path/CVS/Repository");

    if ($repository) {
        process_rep($path, $repository);

        ProcessCVSEntries($path, "$path/CVS/Entries", $pattern);
    }

    opendir(DIR, $path) or warn "$!: reading $path\n";
    my @files= readdir DIR;
    closedir DIR;

    # recurse into subdirectories
    for my $filename (@files) {
        next if ($filename eq "." || $filename eq "..");
        my $fullpath = "$path/$filename";
        if (-d $fullpath)
        {
            if ($filename ne "CVS") {
                ProcessDirectory($fullpath, $pattern);
            }
        }
    }
}


