#! /bin/bash

# md5sum search and recover for /lost+found
#
# (c) 2004 Leading Edge Business Solutions and Andrew McGill
# May be distributed under the terms described in the COPYING
# file (GPL)

DIR=.recovery
if [ -d /var/lib/dpkg/info ] ; then
	DPKG=1
else
	DPKG=
fi

# Make md5sums and look them up in the rpmdb
function md5search()
{

mkdir -p $DIR
echo Making md5sums of current directory to $DIR/md5sums
find -type f -maxdepth 1 | xargs md5sum > $DIR/md5sums

echo Stripping md5sums from names to $DIR/md5
cut -f 1 -d ' ' <$DIR/md5sums >$DIR/md5

# dpkg -- just assume it's debian
if [ $DPKG ] ; then
	echo Searching /var/lib/dpkg/info for md5sums to $DIR/dpkginfo
	cat  /var/lib/dpkg/info/*.md5sums |
	fgrep -f $DIR/md5 | sed 's:  : /:' > $DIR/dpkginfo

	echo Joining to $DIR/mapping
	join -1 1 -2 1 -o 1.2,2.2 $DIR/md5sums $DIR/dpkginfo > $DIR/mapping
else
	echo Searching rpm -qa --dump for md5sums to $DIR/rpmdb
	rpm -qa --dump | fgrep -f $DIR/md5 > $DIR/rpmdb

	echo Joining to $DIR/mapping
	join -1 1 -2 4 -o 1.2,2.1 $DIR/md5sums $DIR/rpmdb > $DIR/mapping
fi

}

# Move the files as located by md5sum ... identical files get lost
function movefiles()
{
echo "Moving files as listed in $DIR/mapping"
while read SRC DST MD5 ; do
	mv --reply=no "$SRC" "$DST"
done < $DIR/mapping
}

# Move the files as located by md5sum ... identical files get lost
function showfiles()
{
while read SRC DST MD5 ; do
	echo "mv --reply=no '$SRC' '$DST'"
done < $DIR/mapping
}

# Query the rpm database and re-make all the directories
function createrpmdirs()
{
# while read path size mtime md5sum mode owner group isconfig isdoc rdev symlink.
echo Checking all directories in rpm database
rpm --dump -qa | grep '  04' |
while read path size mtime mode owner group isconfig isdoc rdev symlink ; do
	mode=${mode/??/}
	if [ ! -d $path ] ; then
		mkdir $path && chown $owner:$group $path && chmod $mode $path 
	fi
done
# while read path size mtime md5sum mode owner group isconfig isdoc rdev symlink.
echo Checking all symlinks in rpm database
rpm --dump -qa | grep '  0120777' |
while read path size mtime mode owner group isconfig isdoc rdev symlink ; do
	mode=${mode/??/}
	if [ ! -e $path ] ; then 
		ln -s "$symlink" $path # && chown $owner:$group $path && chmod $mode $path 
	elif [ ! -h $path ] ; then 
		echo "$path: not symbolic link!"
	fi
done
}

# Clean up working files
function cleanup()
{
	rm -f $DIR/md5sums $DIR/md5 $DIR/rpmdb $DIR/mapping $DIR/dpkginfo
	rmdir $DIR
}


function usage()
{
echo "Usage: $0 [md5|move|dirs]"
echo ""
echo "  md5     look up md5 sums for ./ in rpm database"
echo "  show    show what we found"
echo "  move    move files according to md5 sums"
echo "  find x  suggest the origin of file x"
[ $DPKG ] ||
echo "  dirs    recreate missing rpm directories and symlinks"
echo "  clean   clean up $DIR"
}

case "$1" in 
	md5)   md5search ;;
	show)  showfiles ;;
	show)  movefiles ;;
	dirs)  createrpmdirs;;
	clean) cleanup;;
	*)     usage;;
esac

