#!/bin/bash
# md5checksum.sh 

usage ()
{
	echo "USAGE:$0 [-r] [path]"
	echo "e.g.: $0 /ST3/information/language/english/科利华英语 "
	echo "e.g.: $0 -r /ST3/information/language/english/科利华英语"
}


if [ $# -gt 2 ]; then
	usage;
	exit 1;
fi

subdir_flag=0
path="./"

## By default, getopts issues an error message if it finds an unrecognized option or some other error. 
## If you do not want such messages printed, specify a colon as the first character in optstring.
## : means "takes an argument"
while getopts ":r" opt; do
	case $opt in
		r)
			subdir_flag=1
			;;
	esac
done

echo "subdir_flag:${subdir_flag}"
if (( subdir_flag==1 ))
then
	if (( $#==2 ))
	then
		path=${2}
	fi
else
	if (( $#==1 ))
	then
		path=${1}
	fi
fi
work_path=$(pwd)
path=`echo ${path}| sed "s/\/$//g"`
	
cd ${work_path}
now_path=""
last_path=""
echo "work_path:${work_path},path:${path}"
file_list=""
if (( subdir_flag==1 ))
then
	echo "find ${path}  -type f | grep -v md5$"
	file_list=`find ${path}  -type f | grep -v md5$`
	##echo "${file_list}"
	IFS='
'
	for  file in ${file_list}
	do
		##echo "file[${file}]"
		now_path=$(dirname "${file}")
		if [[  "${now_path}" != "${last_path}" ]];then
			if [[  "${last_path}" != "" ]];then
				cd -
			fi
			cd ${now_path}
			echo "cd ${now_path}"
			last_path=${now_path}
		fi
		file_name=$(basename "${file}")
		echo "file_name:${file_name}"
		md5sum "${file_name}"  >  "${file_name}.md5"
		##echo "md5sum $(basename ${file})  >  $(basename ${file}).md5"
	done

else
	cd ${path}
	echo "ls -1F | grep -v /$ | sed \"s/\*$//g\" | grep -v md5$"
	file_list=`ls -1F | grep -v /$ | sed "s/\*$//g" | grep -v md5$ `
	IFS='
'
	for  file in ${file_list}
	do
		md5sum "${file}"  >  "${file}.md5"
		##echo "md5sum ${file}  >  ${file}.md5"
	done
fi

exit 0
