#!/usr/bin/perl
# A wrapper for find, which knows about cruft IGNORES and filesystems to scan
# or not to scan.
use strict;
use warnings;

sub usage { "cruft_find <target> [ <target> ... ] [ option ... ]\n" }

my (@args, @params);
my $dest = \@args;
foreach (@ARGV) { $dest = \@params if /^-/; push @$dest, $_; }
@args or die &usage;

require '/usr/lib/cruft/common.pl';
sub is_subdir($$);
sub ignores;
sub scan_fs;
sub all_fs;
sub noscan_fs;
sub get_direct_fs($@);
sub prunes($@);

sub do_find($)
{
	my $path = shift;
	my $FS = get_direct_fs($path, all_fs);
	warn "FS not found for \"$path\"" and return unless $FS;
	my @do_scan = scan_fs;
	my @dont_scan = noscan_fs;
	my @ignore = ignores;
#	use Data::Dumper 'Dumper';
#	warn Dumper({FS=>$FS,path=>$path,doscan=>\@do_scan,dont=>\@dont_scan,ignore=>\@ignore});

	# $path is below ignored subtree
	return if grep { is_subdir($_, $path) } @ignore;
	# $path is in non-scan FS
	if (grep { $_ eq $FS } @dont_scan) {
		# and contains no do-scan FS
		if (grep { is_subdir($path, $_) } @do_scan) {
			return;
		} else {
		# TODO: and contains some do-scan FS
		# foreach (NI under $path) find $NI -xdev
			;
		}
	}
	# $path is in do-scan FS
	elsif (grep { $_ eq $FS } @do_scan) {
		# and there are no dont-scan FS under $path
		if (not grep { is_subdir($path, $_) } @dont_scan) {
			my $cmd = "find $path ".prunes($path, @ignore).' '.join(' ', @params);
			print STDERR "Running [$cmd]\n" if exists $ENV{'CRUFT_DEBUG'};
			system($cmd);
		} else {
		# TODO: and there are dont-scan FS under $path
		# foreach (NI under $path) find NI -xdev
			;
		}
	} else { die "Internal error: [$path][@do_scan][@dont_scan][@ignore]\n"; }
	
}

do_find($_) for @args;

