#!/bin/bash

# -------------------------------------------------------
# RPC Project :
# Run RPC_convert_names of a given directory
# P. Robert, ScientiDev, Dec. 2021
# -------------------------------------------------------

appli=`basename $0`
appli36=`echo "$appli                                 " | cut -c1-36`
Narg=1

if( (test $# = 1 ) && (test $1 = -h ) ) ; then hh=1 ; else hh=0 ; fi

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : Convert recursively files name having blank or special character"
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   /media/robert/robib " 
   echo "               path must be absolute path"
   echo ""
   if test $hh = 1 ; then exit 0 ; fi
   echo " $appli36 : *** ERROR ! Command aborted." >&2
   exit 1
fi

echo " -------------------------------------------------------------------"
echo "$appli $*"
echo " -------------------------------------------------------------------"
echo ' '


pcar=`echo $1 | cut -c1`

if test $pcar != /
   then echo "directory : $1"
        echo "*** pathname must begin by '/'"
   exit 3
fi

if test -d $1
   then echo "convert all file name in the tree of $1"
   else echo
        echo "*** directory $1 does not exist"
        exit 2
fi

find $1 -type d > toto.tmp
echo
grep ' ' toto.tmp

if test $? = 0
   then echo
        echo "*** there is blank in the previous directories"
        echo "    please correct it before correct all the files"
        exit 1
fi


for dir in `cat toto.tmp`
    do
    cd $dir
	pwd
    for f in *; do nf=$(echo "$f" |sed -e 's/[^A-Za-z0-9.-]/_/g;s/\.\.\././g;s/\.\././g'); test "$f" != "$nf" && mv "$f" "$nf" && echo "$nf"; done
    cd $1
done

rm toto.tmp