#!/bin/bash

if [ "$1" == "conv2utf" ]
    then
    fname=`echo "$3" | iconv -f koi8-r -t utf-8 2>/dev/null`
    if [ "$?" == "0" -a "$3" != "$fname" -a -n "$3" -a -n "$fname" ]
	then
	testcorrect=`echo "$fname" | sed -e "s/[-А-Яа-я0-9A-Za-z (),!./]//g" -e "s/[][&_\"\']//g"`
	if [ -z "$testcorrect" ]
	    then
	    if [ "$2" == "justprint" ]
		then
		echo "will mv $3 to $fname"
	    else
		echo "moving $3 to $fname"
		mv "$3" "$fname"
	    fi
	fi
    fi
else

#get fullname of the script
    pushd $(dirname ${0}) >/dev/null
    DIR=$(pwd)
    SNAME=${DIR}/$(basename ${0})
    popd >/dev/null
    
    
    if [ -z "$1" -o '(' "$1" != "justprint" -a "$1" != "doit" ')' ]
	then
	echo "Script to convert directory tree from koi8-r to utf-8"
	echo "Usage:"
	echo "${SNAME} [justprint|doit [directory]]"
	echo "Will convert all files and directories in specified directory"
	echo "If directory is not specified, will start in current direcory"
	echo "With 'justprint' - do not do renaming, just print what will"
	echo "be done. To do actual renaming, you should say 'doit'."
	echo "You can start this script as much as you like on the same "
	echo "directory tree. Since it makes some checking, there will be"
	echo "no reencoding."
	exit 0
    fi
	
    find $2 -type d -exec bash -c 'pushd "{}">/dev/null; find . -maxdepth 1  -print0| xargs --null -n 1 '${SNAME}' conv2utf '${1}'; popd >/dev/null' \;
    
fi
