#!/usr/bin/perl

#
# Script: afind, a version of find for AFS
# Author: Francisco Lozano - Cern (20-Feb-96)
#

require 'getopts.pl';   # Subroutines: Getopts.
require "shellwords.pl";


$DEBUG = 0;

if (!($ARGV[0] =~ /^-/)) {
    $DIR = $ARGV[0]?$ARGV[0]:".";
    shift @ARGV;
} else {
    $DIR = ".";
}

if (!&Getopts ('h:n:e:t:d')) {
    &Usage;
}

$DEBUG = 1 if $opt_d;

&Usage if $opt_h;
$opt_n =~ s/([\*\?])/\.$1/g if $opt_n;

&action($DIR) if !&check_file($DIR);
&scan_dir ($DIR);
 
sub scan_dir {
    my ($path) = @_;
    my (@dir, $entry, $ext_path);

    opendir DIR, $path;
    @dir = readdir DIR;
    close DIR;
    for $entry (@dir) {
	$ext_path = "${path}/${entry}";
        next if ($entry =~ /^\.{1,2}$/);
        next if &check_file($entry);
        if (-d $ext_path) {
	    ($dummy, $inode) = stat ($ext_path);
	    if ($inode % 2 == 0) {
 		# It is a mount point 
		next;
	    } else {
	        &action($ext_path);    
		&scan_dir ($ext_path);
	    }
	} else {
	    &action($ext_path);    
	}
    }
}

sub action {
    my ($ext_path) = @_;
    my ($cmd,$word);
    my ($tmp);

    if ($opt_n) {
	print "Opt name: $opt_n\n" if $DEBUG;
	$ext_path =~ /([^\/]*)$/;
	print "name: $1\n" if $DEBUG;
	return if !($1 =~ /^$opt_n$/);
    }
    if ($opt_t) {
	print "Opt type: $opt_t\n" if $DEBUG;
	return if !(eval"-$opt_t ('$ext_path')");
    }
    if ($opt_e) {
	@cmd = &shellwords($opt_e);
        foreach $word (@cmd) {
            $word =~ s#{}#$ext_path#g;
        }
	$tmp = join (" ", @cmd);
	print "Command: $tmp\n" if $DEBUG;
	system @cmd;
    } else {
	print "$ext_path\n";
    }	
}

sub check_file {
    my ($file) = @_;
    my($rc);

    $rc = ($file =~ /[`]/);
    return $rc;
}

sub Usage {
    print "Usage: afind [path] [-t <type>] [-n <regexpr>] [-e \"<command>\"] [-help]";
    print ", {} is replaced by current path name inside the command.\n"; 
    exit 1;
}
