#!/usr/bin/perl

# Not using "-w" to keep command-line expression flexible.

# $Id: pern,v 1.2 2022/09/29 01:47:43 bscott Exp bscott $

# Name:
# 	pern - "Perl Expression ReName",
# Purpose:
#	A utility to rename files, based on a Perl expression.
# Usage:
#	rename [options] <oper> <files>
# Options:
#	-v	verbose; display each rename before doing it
#	-n	no-op; don't actually do the rename, just test
# Examples:
# 	pern 's/\.orig$//' *.orig
#	pern 'y/A-Z/a-z/ unless /^Make/' *
#	pern '$_ .= ".bad"' *.f
#	pern 'print "$_: "; s/foo/bar/ if <stdin> =~ /^y/i' *

# includes
use Getopt::Long;
# Not using "strict" to keep command-line expression flexible.

# vars
my $progname;
my $verbose;
my $noop;
my $was;
my $op;

# get program name, sans /path/to/it
($0 =~ m/([^\/]+)$/) or die "could not get program name";
$progname = $1;

# get options (if any)
die ("command line parse error") if not GetOptions(
	'verbose'	=>	\$verbose,
	'v'		=>	\$verbose,
	'n'		=>	\$noop,
	'd'		=>	\$debug,
	);

# get operation from command line
($op = shift) or die "$progname: No operation specified\n";

warn("op=<$op>\n") if $debug;

# make sure we have some files
die "$progname: No files specified\n" if (@ARGV < 1);

# loop through each file name argument
for (@ARGV) {
	# save old name from $_ to $was
	$was = $_;
	warn("was=<$was>\n") if $debug;
	# do the op on the name
	eval $op;
	# abort if the eval barfed
	die $@ if $@;
	# skip the rename if the names are the same
	warn("new=<$_>\n") if $debug;
	next if ($was eq $_);
	# skip the rename if target exists
	if ((-l $_) or (-e $_)) {
		warn("$progname: '$was' -> '$_': Target name exists\n");
		next;
	}
	# option handling
	print "'$was' -> '$_'\n" if $verbose;
	next if $noop;
	# do the rename
	rename ($was, $_) or
		warn("$progname: Could not rename '$was' to '$_': $!\n");
}

# END OF FILE
