#/bin/bash
# Author: Emiliano Gabrielli (aka AlberT)
# Last Revision: 2006/11/20
#
# does some sanification on a given directory structure
#

function p_help()
{
	cat 1>&2 <<-EOF
	
	This script does a basic directories and filenames sanification, 
	removing all non wanted characters and substituting them with a 
	single underscore.
	By default admitted characters are "A-Za-z0-9_-", while "/" and "." 
	are enforced to be preserved.

	Usage: $0 <path> [<allowed_characters>]
	
	EOF
	exit 1;
}

function pwd_sanify()
{
	IFS=$'\n' ; for f in $(find $1 -maxdepth 1 -iregex .*[^./${chars}]+.* )
	do
		mv -- $f `echo $f | sed -e 's#/-#/#' | sed -e "s#[^./${chars}]\+#_#g"`
	done
	
	for d in `find $1 -maxdepth 1 -type d` ; do
		if [[ "$d" != "$1" ]] ; then
			pwd_sanify $d
		fi
	done
}


######### main ############

if [[ $#<1 || $#>2 ]] ; then
	p_help;
fi

path="${1:-./}";
if [ ! -d $path ] ; then
	echo "The given argument '${path}' seems not to be a directory" 1>&2 ;
	exit 1;
fi

chars="${2:-A-Za-z0-9_-}";
echo "Working on ${path}";
echo "Allowed characters are: '${chars}'";
echo

pwd_sanify ${path};

echo done;
exit 0;


