#!/bin/bash
# md5verify.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

time=`date +"%Y%m%d%H%M%S"`
logname=md5check_list_${time}.txt

work_path=$(pwd)

logpath=${work_path}/${logname}
path=`echo ${path}| sed "s/\/$//g"`
	
cd ${work_path}
: > ${logpath}
echo  "start : " `date` | tee -a ${logpath}
now_path=""
last_path=""
echo "work_path:${work_path},path:${path}" | tee -a ${logpath}
file_list=""
if (( subdir_flag==1 ))
then
	echo "find ${path}  -type f | grep md5$"
	file_list=`find ${path}  -type f | grep md5$`
	IFS='
'
	for  file in ${file_list}
	do
		now_path=$(dirname "${file}")
		if [[  "${now_path}" != "${last_path}" ]];then
			if [[  "${last_path}" != "" ]];then
				cd -
			fi
			cd ${now_path}
			echo "cd ${now_path}" | tee -a ${logpath}
			last_path=${now_path}
		fi
		file_name=$(basename "${file}")
		##md5sum -c "${file_name}"
		result=$(md5sum -c ${file_name})
		printf "%-100s: %2s\n"  ${result%:*}  ${result##*:} | tee -a ${logpath}
		##echo "md5sum -c $(basename ${file})"
	done

else
	cd ${path}
	echo "ls -1F | grep -v /$ | sed \"s/\*$//g\" | grep md5$"
	file_list=`ls -1F | grep -v /$ | sed "s/\*$//g" | grep md5$`
	IFS='
'
	for  file in ${file_list}
	do
		result=$(md5sum -c ${file})
		printf "%-100s: %2s\n"  ${result%:*}  ${result##*:} | tee -a ${logpath}
		##echo "md5sum -c ${file}"
	done
fi


echo  "end : " `date` | tee -a ${logpath}

exit 0


