#!/bin/bash
# $Id: oddb_lst 31 2010-01-23 15:10:40Z winex $

# this script calculates md5sums of all files found under specified path, excluding
# 'md5sums', '*md5lst'
# if first argument is 'md5sums', it will take md5's from it and output md5lst

path_arg=
name_arg=
md5sums=

if [ -n "$1" ]; then
    path_arg=$1
    check=`basename "$path_arg"`
    if [ "$check" == "md5sums" ]; then
	md5sums="$path_arg"
    fi
else
    echo "Usage: ${0##*/} PATH_TO_ROOT [NAME_REGEX]"
    exit 0
fi

if [ -n "$2" ]; then
    name_arg="$2"
else
    name_arg="*"
fi


if [ -n "$md5sums" ]; then
    cat "$md5sums" | while read line
    do
	md5=${line:0:32}
	fname=${line:34}
	printf "$md5\t`stat -c%s "$fname"`\t$fname\n"
    done
    exit 0
fi


# holy shit here :O
tmpf=/tmp/sed-scr$$.tmp
echo 's/\([\/\\\.]\)/\\\1/g' >$tmpf
path_rpl=`echo "$path_arg" | sed -f $tmpf`
rm $tmpf

# do it :)
# TODO: 20080126 winex: replacing 2 consecutive spaces to tabs everywhere not as good as it seems :)))
find "$path_arg" -type f -name "$name_arg" ! -name "md5sums" ! -name "md5lst" -printf "%s\t" -exec md5sum {} \; | \
	sed 's/ [ \*]/\t/' | sed "s/${path_rpl}[\/?]*//" | sed 's/\([0-9]*\t\)\([0-9a-f]*\t\)/\2\1/' | \
	LC_ALL=C sort -t$'\t' -k3,3

## TODO: 20070926 winex: use sorting of output
#env LC_ALL=C sort -t '	' -k 3,3
