#!/usr/bin/perl
#
# Fabulous demonstration of the Power of Perl
#	.. taken from the camel book ..
#
# added ability to rename files in depth
# added -r option for recursion
# added -n option for no op
# added protection against erroneous overwriting
# added -f to overwrite files
#					-symLynX
#
use locale;

require 'getopt.pl';
&Getopt;

require 'find.pl' if $opt_r;

$op = shift or die "Usage: $0 " . <<'X';
[options] [perlexpr] [filenames]

options:
	-r(ecurse)		surf deep into directories
	-n(o operation)		just pretend and show what you would do
	-f(orce)		do overwrite files

examples:
	rename 's:(.*):\L\1\E:' *
				 (changes all filenames to lowercase)
	rename 's:\.(\w+)$:-old.\1:' */*.html
				 (rename all */*.html to */*-old.html)
X

if (!@ARGV) {
    @ARGV = <STDIN>;
}

for (@ARGV) {
    &find($_) if $opt_r && -d $_;
    &wanted($_);
}

sub wanted {
    $path = '';
    ($path, $_) = ($1,$2) if m!^(.*/)([^/]+)$!;

    $was = $_;
    eval $op;
    die $@ if $@;

    if ($was ne $_) {
	if (!$opt_f && -e "$path$_") {
	    # this added safety may be ununixish, but i found it
	    # definitely useful!	-symlynx
	    #
	    print STDERR "$_ already exists! $was NOT renamed to $_\n";
	} else {
	    print "cd $path && " if $path;
	    print "mv $was $_\n";
	    rename("$path$was", "$path$_") unless $opt_n;
	}
    }
}
