#!/bin/ksh
# @(#) rename.ksh 1.1 94/05/10
# 90/06/01 John DuBois (spcecdt@armory.com)
# 91/02/25 Improved help info
# 92/06/07 remove quotes from around shell pattern as required by new ksh
# 94/05/10 Exit if no globbing chars given.

if [ "$1" = -t ]; then
    tell=true
    shift
fi

if [ "$1" = -v ]; then
    verbose=true
    shift
fi

if [ $# -lt 2 ]; then
    echo \
"Usage: rename oldpattern newpattern
All files that match oldpattern will be renamed with the
filename components that match the constant parts of oldpattern
changed to the corresponding constant parts of newpattern.
The components of the filename that match variable parts of
oldpattern will be preserved.  Variable parts in oldpattern
must occur in the same order in newpattern.  Variables parts
can be '?' and '*'.
Example: 
rename \"/tmp/foo*.ba.?\" \"/tmp/new*x?\"
All files in /tmp that match foo*.ba.? will have the \"foo\" part
replaced by \"new\" and the \".ba.\" part replaced by \"x\"."
    exit
fi

oldpat=$1
newpat=$2

set $1
if [[ ! -a $1 ]]; then
    echo "No files match $oldpat."
    exit
fi

typeset -i i=1 j

# For old ksh
# while [[ "$oldpat" = *'[\*\?]'* ]]; do

# Example oldpat: foo*.a
# Example newpat: bar*.b

# Examples given for first iteration (in the example, the only interation)
while [[ "$oldpat" = *[\*\?]* ]]; do
    # Get leftmost globbing pattern in oldpat
    pat=${oldpat#*[\*\?]}	# pat=.a
    pat=${oldpat%%"$pat"}	# pat=foo*
    pat=${pat##*[!\?\*]}	# pat=*
    # Find parts before & after pattern
    oldpre[i]=${oldpat%%"$pat"*}	# oldpre[1]=foo
    oldsuf[i]=${oldpat#*"$pat"}		# oldsuf[1]=.a
    newpre[i]=${newpat%%"$pat"*}	# newpre[1]=bar
    # Get rid of processed part of patterns
    oldpat=${oldpat#${oldpre[i]}"$pat"}	# oldpat=.a
    newpat=${newpat#${newpre[i]}"$pat"}	# newpat=.b
    let i=i+1
done

if [ i -eq 1 ]; then
    print -u2 "No globbing chars in pattern."
    exit 1
fi

oldpre[i]=${oldpat%%"$pat"*}	# oldpre[2]=.a
oldsuf[i]=${oldpat#*"$pat"}	# oldsuf[2]=.a
newpre[i]=${newpat%%"$pat"*}	# newpre[2]=.b

if [ -n "$verbose" ]; then
    j=1
    while [[ j -le i ]]; do
	echo \
"Old prefix: ${oldpre[j]}   Old suffix: ${oldsuf[j]}   New prefix: ${newpre[j]}"
	let j=j+1
    done
fi

# Example file: foox.a

for file; do
    j=1
    origname=$file	# origname=foox.a
    newfile=
    while [[ j -le i ]]; do
	# Peel off a prefix	interation	1		2
	file=${file#${oldpre[j]}}		# file=x.a	file=
	# Save the part of this prefix that is to be retained
	const=${file%${oldsuf[j]}}		# const=x	const=
	newfile=$newfile${newpre[j]}$const	# newfile=barx	newfile=barx.b
	file=${file#$const}			# file=.a	file=.a
	let j=j+1
    done
    if [ -n "$tell" ]; then
	echo "Would move \"$origname\" to \"$newfile\"."
    else
	if [ -n "$verbose" ]; then
	    echo "Moving \"$origname\" to \"$newfile\"."
	fi
	mv $origname $newfile
    fi
done
