#!/bin/sh
#\- rename files; substitute string, or pre/append date or string, or convert to lower case, or truncate; SLOW
#usage: %rename   
#	[-x] { {-l,-u,-number}, {-a,-p,oldstring} {-d,newstring} }  filelist
#rename a set of files, 
#by substituting oldstring by newstring in each filename
#by appending|prepending (-a|-p) the newstring or a date (-d)
#by converting all to lower case (-l) or upper case (-u)
#query before making each change
#NOTE: slow but sure
#j.a. rupley, tucson, arizona

BNM=`basename $0`
USAGE="
$BNM  [-x] { {-l|-u|-number} | {{-a|-p|oldstring} {-d|newstring}} }  filelist
	$BNM  abc  xyz  *	converts all files *abc* to *xyz*
	$BNM  -p   xyz  *		prepends xyz to all files
	$BNM  -a   xyz  *		appends xyz to all files
	$BNM  -d   -[a|p] *	[ap|pre]pends date to all files
	strings may be regular expressions
	each conversion is queried for  [y|n|q|cr]
	options:	-x no query
			-a [-p] appends [prepends] newstring
			-d sets newstring to today's date -yymmdd-
			-l [-u] convert upper to lower case [or reverse]
				(no substitutions or ap(pre)pending allowed)
			-number truncate filename to <number> characters
				(no substitutions or ap(pre)pending allowed)"

if [ $# -lt 1 ]
then
	/bin/echo "$USAGE"
	exit 1
fi
noquery=`/bin/expr 0`
lower=`/bin/expr 0`
upper=`/bin/expr 0`
truncate=`/bin/expr 0`
while [ `/bin/echo $1 | /usr/bin/cut -c1` = "-" ]
do
	case $1 in
	-a)	oldstr='$'
		shift
		;;
	-p)	oldstr='^'
		shift
		;;
	-d)	newstr=`/bin/date +%y%m%d`
		shift
		;;
	-x)	noquery=`/bin/expr 1`
		shift
		;;
	-l)	lower=`/bin/expr 1`
		shift
		;;
	-u)	upper=`/bin/expr 1`
		shift
		;;
	-[0-9][0-9]*)	truncate=`echo $1 | cut -c2-`
		shift
		;;
	-*)	/bin/echo "$USAGE"
		exit 1
		;;
	esac
done

if [ \( $lower -eq 0 \) -a \( $upper -eq 0 \) -a \( $truncate -eq 0 \) ]
then
	if [ $oldstr"x" = "x" ]
	then
		oldstr=$1
		shift
	fi
	if [ $newstr"x" = "x" ]
	then
		newstr=$1
		shift
	fi
fi

if [ $# -lt 1 ]
then
	/bin/echo "$USAGE"
	exit 1
fi

for i
do
	if [ $lower -eq 1 ]
	then
		aaa=`/bin/echo $i | /usr/bin/tr "[A-Z]" "[a-z]"`
	elif [ $upper -eq 1 ]
	then
		aaa=`/bin/echo $i | /usr/bin/tr "[a-z]" "[A-Z]"`
	elif [ $truncate -ne 0 ]
	then
		aaa=`/bin/echo $i | cut -c1-$truncate`
	else
		aaa=`/bin/echo $i | /usr/bin/sed /$oldstr/s//$newstr/`
	fi
	if [ "$aaa" ]
	then
	    if [ $noquery -eq 0 ]
	    then
		/bin/echo "$i -> $aaa    ok? \c"
		read RESPONSE
		bbb=`/bin/echo $RESPONSE | /usr/bin/cut -c1`
		if [ $bbb"x" = "yx" ]
		then
			/bin/mv $i $aaa
#			/bin/echo $i $aaa
		elif [ $bbb"x" = "qx" ]
		then
			exit 0
		fi
	    else
		/bin/mv $i $aaa
	    fi
	fi
done
