#! /bin/sh

# Called with:
#   $1 = %patches
#   $2 = %name of patch package
#   $3 = %kversion

name="i2c"
version="2.8.3"

temp_dir="`mktemp -d -t patch.XXXXXXXXXX`" || exit 1

exit_handler()
{
	local rc=$?
	trap - EXIT
	rm -rf -- "$temp_dir" ||:
	exit $rc
}
trap exit_handler EXIT HUP INT QUIT PIPE TERM

tar -xj -f "$1/$2/$name-$version.tar.bz2" -C "$temp_dir" || exit 1

srcdir="$temp_dir/$name-$version"

perl "$srcdir/mkpatch/mkpatch.pl" "$srcdir" . | patch -p1 -E


# Apply additional patches (copied from kernel-build-tools RPM macros)

function apply_recursive()
{
	for i in `ls -1 $1` ; do
		if [ ! -s "$1/$i" ] ; then continue ; fi
		if [ -f "$1/dont_apply_to_${3}_$i" ] ; then
			echo "Denied for the kernel version $3 ..."
			continue
		fi
		if [ -d "$1/$i" ] ; then
			if [ -f patches/APPLIED_`echo $i | sed -e 's/^.._\\(.*\\)/\\1/'` ] ; then
				apply_recursive "$1/$i" "$2" "$3"
			fi
			continue
		fi
		echo "Applying patch $i ..."
		patch -p1 -b < "$1/$i" || return 1
	done
}

apply_recursive "$1/$2/patches" "$1" "$3"
