#!/bin/bash
# checkFile
#
#	Purpose:
#		
#	Description:
#		
#	History:
#		Thu Nov 17 09:43:23 TST 2011, Created by jumperchen
#
#Copyright (C) 2011 Potix Corporation. All Rights Reserved.
#
if [ $# != 2 ] && [ $# != 4 ] ; then
	echo Please specify two files or two folders
	echo for example,
	echo ./bin/checkFile folder1 folder2
	echo To replace version number in each file/folder, put version number in front of the file/folder names
	echo for example,
	echo ./bin/checkFile 6.0.0 folder1 6.0.1 folder2
	exit 1
fi

if [ $# != 4 ] ; then
	folder1=$1
	folder2=$2
else
	ver1=$1
	folder1=$2
	ver2=$3
	folder2=$4
fi

if [ ! -d "$folder1" ] && [ ! -f "$folder1" ] ; then
	echo $folder1 is not a file or folder
	exit 1
fi
if [ ! -d "$folder2" ] && [ ! -f "$folder2" ] ; then
	echo $folder2 is not a file or folder
	exit 1
fi

maindir="$(pwd)"
tmpdir="$maindir"
os="$(uname)"

if [ $os == "Darwin" ]; then
	tmpdir=$TMPDIR
fi

tmp1="checktmp1"
tmp2="checktmp2"
function checkFile {
	echo $(pwd)/$1
	#echo "List file name $(pwd)/$1" >> $maindir//$2.log
	result=$(echo "$1" | awk '/tar.gz$/{print "yes"}')
	if [ "$result" != "yes" ] ; then
		unzip -ql $1 | awk '{print $4}' | sort >> $tmpdir/$2.log
	else
		tar -tf $1 | sort >> $tmpdir//$2.log
	fi
}
function listFile {
	for f in `ls | sort`; do
		if [ ! -d "$f" ] ; then
			result=$(echo "$f" | awk '/.md5$/{print "yes"}')
			if [ "$result" != "yes" ] ; then
				checkFile "$f" "$1"
			fi
		else
			cd "$f"
			listFile "$1"
			cd ..
		fi
	done
}

if [ -f "$maindir/$tmp1.log" ] ; then
	rm $maindir/$tmp1.log
fi
if [ -f "$maindir/$tmp2.log" ] ; then
	rm $maindir/$tmp2.log
fi

if [ ! -d "$folder1" ] ; then
	checkFile "$folder1" "$tmp1"
else
	cd "$folder1"
	listFile "$tmp1"
fi

if [ ! -d "$folder2" ] ; then
	checkFile "$folder2" "$tmp2"
else
	cd "$folder2"
	listFile "$tmp2"
fi

cd $tmpdir

if [ $# != 2 ] ; then
	sed -i "s/$ver1/{VER}/g" $tmp1.log
	sed -i "s/$ver2/{VER}/g" $tmp2.log
fi

diff $tmp1.log $tmp2.log
if [ $? != 0 ] ; then
	if [ -f TortoiseMerge.exe ] ; then
		TortoiseMerge.exe $tmp1.log $tmp2.log
	elif [ $os == "Darwin" ]; then
		opendiff $tmp1.log $tmp2.log
	else 
		vimdiff $tmp1.log $tmp2.log
	fi

else
	echo "All files are matched!"
fi

if [ $os != "Darwin" ]; then
	rm $tmp1.log
	rm $tmp2.log
fi
