#!/bin/bash
set -e

##	convert-winhashfiles	(aka. [k|g]convert-winhashes)	v0.3
#
#	A part for "Checksum for Linux"
#
#	This script converts windows hash files to UNIX hash files.
#	Essentially, it searches for .md5, .sha1 and .hash files in a 
#	given path, and switches their linebreaks from "\r\n" (aka. 
#	CRLF/DOS carriage returns) to "\n" UNIX Linebreaks. Very sipmle.
#

# :BEGIN PREFS
#

# temporary file..
# It's just a place you can go look to see what happened, if required.
# It is deleted at bootup.
tmpfile="/tmp/checksum.tmp"

#
# :END PREFS


# init..
me=${0##*/}
path=$1

case "$me" in
	kconvert-winhashes)
		zen=1
		;;
	convert-winhashes)
		zen=0
		;;
esac


if [ ! -x /usr/bin/zenity ] && [ $zen -eq 1 ]; then
	zen=0
	echo "***	NOTE	***"
	echo "This script can use zentiy to display dialogs in your window manager. "
	echo "To install zenity (on a Debian-based system, like Kubuntu) do.."
	echo "sudo apt-get install zenity"
	echo "For other systems, check your package manager's man page."
	echo
	#exit 7
fi

if [ "$path" = "" ]; then
	if [ $zen -eq 1 ]; then
		zenity	--question --title "Error!!!" \
				--text "Something bad happened. Please reinstall checksum!" \
				--width=280 --timeout=20 --window-icon="$HOME/.local/share/icons/checksum.png"
	else
		echo
		echo "  *** NO PATH SPECIFIED! ***"
		echo
		echo "Usage: "$me" </path/to/hash/files>"
		echo
	fi
	exit 1
fi


# if [ $kdg -eq 1 ]; then
# 	kdialog --warningyesno "Are you sure you wish to convert all .md5 and .hash files in $1?" \
#			--title "Convert Hash Files?" --dontagain "checksum:dontaskagain_convert"
# fi

if [ $zen -eq 1 ]; then
	zenity 	--notification --title "Windows Hash File Conversion" --text="Conversion in progress. This may take a moment." \
			--window-icon="$HOME/.local/share/icons/checksum.png" &
	notifypids="$!"

else
	echo "converting windows hashes in $path"
	echo "This may take a moment.."
	echo
fi

# a folder ..
if [ -d "$path" ];then
	cd "$path"
	find . -type f \( -name '*.md5' -o -name '*.sha1' -o -name '*.hash' \) -print | while read i;
		do
			if [ -f "${i}" ]; then
				sed -i -e 's/\r//g' "${i}" | tee -a "$tmpfile"
			fi
		done
# a regular file..
else
	sed -i -e 's/\r//g' "$path" | tee -a "$tmpfile"
fi


if [ $zen -eq 1 ]; then
	tail "$hashfile" | zenity	--info ---title="Checksum" --text="All done with conversion!" \
								--window-icon="$HOME/.local/share/icons/checksum.png"
	kill "$notifypids"
else
	echo
	echo "All done with conversion!"
	echo
fi

exit 0
