#! /usr/bin/perl

do "getopts" || die "Can't include getopts";
do Getopts('cdhimnqr');

if ($opt_h) {
    print <<END;
Usage: $0 [-cdimnqr] expr file ...

  expr: valid perl expression that modifies \$_
  file: zero or more filenames.

Rnm applies expr to each of the file names and renames the files
to the new names (if the name has changed). If no filenames are given
filenames are read form STDIN.

Options:

    -d or -n print what would happen but do not execute
    -q (quiet) do not print what happens
    -i (interactive) ask for confirmation for each file
       (y => yes; n => no; q => quit; a => all)
    -m execute a "Copy & Delete" for each change rather than renaming
       useful for moving across file systems
    -c copy rather than rename (using "copy")
    -r with -m or -c, gives R (recursive) option to the copy command

Generally, the safer options take precedence over the less safe ones.
END
    exit;
}

die "Usage: $0 [-cdimnqr] s/x/y/ file ...\n       $0 -h for help\n"
    unless @ARGV;

$expr = shift;
$opt_d += $opt_n;
$opt_q = 0 if $opt_i || $opt_d;
$rflag = $opt_r ? "R" : "~R";

$args = @ARGV;

while (defined ($_ = $args ? shift(ARGV) : <STDIN>)) {
    chop unless $args;
    $old = $_;
    eval $expr;
    if ($@) {
	$_ = $@;
	s/file.*tokens//;
	die "$_\n";
    }
    $eol = $opt_i > $opt_d ? "? " : "\n";
    $new = $_;
    if ($old ne $new) {
	print "$old -> $new$eol" unless $opt_q;
	unless ($opt_d || $opt_i && ! &confirm) {
	    if ($opt_c) { $res = ! system "Copy $old $new ~FQ~C~V$rflag"; }
	    elsif ($opt_m) { $res = ! system "Copy $old $new ~FQ~C~VD$rflag"; }
	    else { $res = rename ($old, $new); }
	    warn "error on $new\n" unless $res;
	}
    }
}

sub confirm {			# ask for confirmation
    ($ans = <STDIN>) =~ s/ *//;
    exit if ($ans =~ /^q/i);
    $opt_i = 0 if ($ans =~ /^a/i);
    return ($ans =~ /^[ay]/i);
}
