#!/bin/sh
# Tests patch applying
# Run with patch[es] for wine project as first param

AGAINSTRELEASE=origin

if [ "$1" = "-r" ] ; then
	AGAINSTRELEASE=release
	shift
fi

if [ "$1" = "-c" ] ; then
	AGAINSTRELEASE=current
	echo "Against current release + patches"
	shift
fi

if [ "$1" = "-h" ] ; then
	echo "Check if patch is applicable to wine source tree"
	echo "Using: checkpatch patch1..."
	echo
	echo "   -r   check against current release vanilla sources"
	echo "   -c   check against current release sources + our patches "
	echo "   -h   this help"
	exit 0
fi

if [ -z "$@" ] ; then
	echo "Run with -h for help"
	exit 1
fi

ORIGWINESOURCE=/srv/wine/Projects/wine-$AGAINSTRELEASE
RL=`readlink $ORIGWINESOURCE`
test -n "$RL" && echo "Against current release ($RL)"

echo

PATCHES=$@

for i in $PATCHES ; do
	if [ ! -r $i ] ; then
		echo "Patch $i is not exists."
		exit 1
	fi
done

TEMPDIR=`mktemp -d`

if [ ! -d $TEMPDIR ] ; then
	echo "Can't create temp dir"
	exit 1
fi


echo "Checking $PATCHES"
FILELIST=`grep "+++ " $PATCHES | cut -d " " -f 2 | sed -e "s|[[:space:]].*||g" | sed -s "s|^b/||"`

for i in $FILELIST ; do
	[ "$i" = "/dev/null" ] && { echo "Skipping $i..."; continue ; }
	echo "Copying $i..."
	#test -f $ORIGWINESOURCE/$i
	install -D -m644 $ORIGWINESOURCE/$i $TEMPDIR/$i #|| mkdir -p `dirname $TEMPDIR/$i`
done

#find $TEMPDIR
RES=0
( cat $PATCHES | sed -e "s|^--- a/|--- |g" | sed -e "s|^\+\+\+ b/|\+\+\+ |g" ; echo ; echo "You have some error in last chunk of the patch" ; echo "Test Line" ) | patch -p0 -d $TEMPDIR && echo -e "\n + + + All applied correctly + + +\n" || RES=1

if [ $RES = 1 ] ; then
	echo "ERROR! Patch is not applied correctly"
	find $TEMPDIR -name "*.rej" | xargs cat
fi

echo "Removing $TEMPDIR..."
rm -rf "$TEMPDIR"
