#!/usr/local/bin/perl
#
# Based on Daniel V. Klein's "rename" utility
# from "Practical Website Maintenance Using Perl - A Cookbook Approach"
#
use Getopt::Std;
use File::Copy;
use POSIX qw(tmpnam);
use File::Basename;

$script_name = basename("$0");

getopts("cnfv") and $op = shift and $| = 1
    or die "Usage: $script_name [-c(opy)] [-n(on-interactive)] [-f(orce)] [-v(erbose)] expr [files]\n";

chomp(@ARGV = <STDIN>) unless @ARGV;

# new file
# By default the tmp file name is /var/tmp/tmpfile . Rename sometimes refuses
# to work from /var/tmp due to different filesystems.
$tmp = "/tmp/".basename(&tmpnam);

for (@ARGV) {

    # old file
    $curr = $_;
    
    open(CURR, "$curr") || die "Can't open $curr: $!";
    open(TMP, ">$tmp") || die "Can't open $tmp: $!";
    
    while (<CURR>) {

	eval $op;
	die $@ if $@;

	print TMP;
    }

    close(CURR); close(TMP);
    
    print "rename $tmp $curr\n" if $opt_v || (!$opt_n);
    
    unless ($opt_n) {
	print "Confirm? ";
	next unless <STDIN> =~ /^[Yy]/;
    }

    unless (move($tmp, $curr)) {
	warn "RENAME ERROR $tmp -> $curr - $!\n";
	next;
    }
}

unlink $tmp;


    
