#! /bin/sh
#
# Written 2003 by Elrond <elrond@samba-tng.org>
# Some more input by Peter Samuelson <peter@samba-tng.org>.

# This script will not work very well for people doing
# _really_ stupid things like putting newlines in their
# filenames.


if [ "$#" -lt 3 ]
then
	echo "Usage: $0 from-charset to-charset directory [...]" >&2
	exit 1
fi

from="$1"
to="$2"

shift;shift


for dir
do
(
	echo "Converting directory $dir from $from to $to"
	cd "$dir" || exit 1

	find . -depth -print | {
	while read f
	do
		d="$(dirname "$f")"
		b="$(basename "$f")"
		n="$(echo "$b" | iconv -f $from -t $to)"
		ret=$?

		if [ $ret -ne 0 ]
		then
			echo "Could not convert name '$f', leaving unconverted" >&2
			n="$b"
		fi

		if [ "$b" != "$n" ]
		then
			if [ "$d" != "$oldd" ]
			then
				echo "    $d"
				oldd="$d"
			fi
			echo "	$b -> $n"
			mv "$d/$b" "$d/$n"
		fi
	done
	}
)
done
