#!/bin/sh -
PATH=/usr/local/bin:/bin:/usr/bin; export PATH

# renam - move or copy files and directories based on a sed or perl script
# Steve Kinzler, steve@kinzler.com, Nov 93/Sep 20
# https://kinzler.com/me/home.html#unix

cmd=mv
ed=sed
verbose=; force=; nodo=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-c)	cmd=cp;;
		-m)	cmd=mv;;
		-p)	ed='perl -p';;
		-s)	ed=sed;;
		-v)	verbose=t;;
		-q)	verbose=;;
		-f)	force=t;;
		-n)	nodo=t; verbose=t;;

		--)	shift; break;;
		-h)	bad=t; break;;
		-*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)	break;;
		esac
		shift;;
	esac
done

case "$#,$bad" in
[01],*|*,?*)	cat << EOF 1>&2
usage: $0 [ -c | -m ] [ -p | -s ] [ -v | -q ]
       [ -f ] [ -n ] script file ...
	-c	copy files and directories based on script
	-m	move files and directories based on script (default)
	-p	interpret script as perl
	-s	interpret script as sed (default)
	-v	verbose output
	-q	quiet output (default)
	-f	force file overwrites and directory replacements
	-n	no execute, just print commands that would execute
\$ENV{I} is available in perl scripts as an incrementing index starting at 1.
EOF
		exit 1;;
esac

script="$1"; shift
status=0

I=0; export I
for old
do
	I=`expr $I + 1`
	old=`echo "$old" | sed 's/\/*$//'`
	new=`echo "$old" | $ed -e "$script"` || exit $?

	case "$new" in
	"$old")	echo "$0: skipping, new name equals old ($old -> $new)" 1>&2
		continue;;
	'')	echo "$0: cannot rename to null ($old -> $new)" 1>&2
		status=2; continue;;
	esac

	if test -f "$new" -o -d "$new"
	then
		case "$force" in
		?*)	r=; test -d "$new" && r=' -r'
			case "$verbose" in
			?*)	echo "rm$r $new";;
			esac
			case "$nodo" in
			'')	rm $r "$new"

				if test -f "$new" -o -d "$new"
				then
					cat << EOF 1>&2
$0: cannot remove destination ($old -> $new)
EOF
					status=3; continue
				fi;;
			esac;;

		*)	echo "$0: file already exists ($old -> $new)" 1>&2
			status=4; continue;;
		esac
	fi

	r=; test "$cmd" = cp -a -d "$old" && r=' -r'
	case "$verbose" in
	?*)	echo "$cmd$r -- $old $new";;
	esac
	case "$nodo" in
	'')	$cmd $r -- "$old" "$new" || status=$?;;
	esac
done

exit $status
