#!/bin/sh
# --- SDE-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# 
# Filename: unify.sh
# Copyright (C) 2006 The OpenSDE Project
# 
# More information can be found in the files COPYING and README.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- SDE-COPYRIGHT-NOTE-END ---

do_unify() {
	local filename="$1" data="$2"
	local count= counti=
	
	counti=$( cut -f1 "$data" | sort -nu | wc -l )
	if [ $counti -gt 1 ]; then
		# different inodes? field for unification

		local reffile= file=
		local refinode= inode=
		local refmd5= md5=
		local sumfiles=

		trap '' INT
		# capture checksums
		rm -f "$data.*"
		while read inode file; do
			if [ ! -f "$data.$inode" -a -r "$file" ]; then
				md5sum "$file" | cut -d' ' -f1 > "$data.$inode"
				sumfiles="$sumfiles $data.$inode"
			fi
		done < "$data"

		# unify
		for refmd5 in $sumfiles; do if [ -r "$refmd5" ]; then
			refinode=${refmd5#$data.}
			refmd5=$( cat $refmd5 )
			reffile=$( grep "^$refinode	" $data | head -n 1 | cut -f2 )

			for md5 in $data.*; do if [ -r "$md5" ]; then
				inode=${md5#$data.}
				if [ "$inode" != "$refinode" ]; then
					md5=$( cat $md5 )
					if [ "$md5" = "$refmd5" ]; then
						for file in $( grep "^$inode	" $data | cut -f2 ); do
							echo "file: $filename ${file%/$filename} -> ${reffile%/$filename} [OK]"
							cp -fl "$reffile" "$file"
						done
						rm "$data.$inode"
						grep -v "^$inode	" $data > $data.tmp
						mv $data.tmp $data
					else
						file=$( grep "^$inode	" $data | head -n 1 | cut -f2 )
						echo "file: $filename ${file%/$filename} ($md5) vs. ${reffile%/$filename} ($refmd5) [FAIL]"
					fi
				fi
			fi; done

			rm "$data.$refinode"
			grep -v "^$refinode	" $data > $data.tmp
			mv $data.tmp $data
		fi; done

		# clean the garbage
		rm -f "$data.*"

		trap - INT
	fi

	rm "$data"
}

do_collect() {
	local location= i=0
	[ $# -gt 0 ] || set -- .

	echo "Collecting data from: $@" >&2

	for x; do
		find "$x" -type f -printf "%f\t$i\t%i\t%p\n"
		i=$(($i + 1))
	done
}

do_process() {
	local tmpfile="$1"
	local prev= next= rest= prio=

	echo "Processing..." >&2
	while read next prio rest; do
		if [ -n "$prev" -a "$next" != "$prev" ]; then
			# data collected, analize
			do_unify "$prev" "$tmpfile.$prev"

			prev="$next"
		elif [ -z "$prev" ]; then
			# first entry
			prev="$next"
		fi

		# collect data
		echo "$rest" >> $tmpfile.$prev
	done
	
	[ -z "$prev" ] || do_unify "$prev" "$tmpfile.$prev"
}

do_collect "$@" | sort | do_process "$$.unify"
