#!/bin/bash
#

usage()
{
cat <<END >&2
Usage: $0 [flags] [--] patch1 [patch2] [...]
Apply a set of patches to a source tree.
For each patch, a new tree is generated by running 'lndir' against the
previous patches.

 -a ARGS	--args=ARGS		Extra arguments to the patch program
					(default '${patchargs}').
		--source=SRCTREE	Names the source tree to use
					(default '${srctree}').
 -v					Select verbose mode
		--verbose=NUM		Selects higher levels of verbosity

 -h		 --help			display this help and exit.
END
}

applyPatch()
{
	[ $verbose -gt 0 ] && echo "Applying patch '${1}' to tree '${2}'" >&2
	if ! $patch $patchargs -d $2 -i $1
	then
		echo "Aborting.  Patch ${1} failed." >&2
		return 1
	fi
	if [ -n "$(find $2 \( -name \*.rej -o -name .\*.rej \) -print)" ]
	then
		echo "Aborting.  Reject files found for patch ${1}." >&2
		return 1
	fi
	find $2 \( -name \*.orig -o -name .\*.orig \) -exec rm -f {} \;
	return 0
}

createTree()
{
	local silent="-silent"
	(
	if [ ! -d $1 ]
	then
		mkdir $1
		[ $verbose -gt 1 ] && echo "Creating directory '$1'" >&2
	fi
	cd $1
	[ $verbose -gt 2 ] && silent=""
	[ $verbose -gt 1 ] && echo "Generating shadow tree for directory '$2' in '$1'" >&2
	case "$2" in
	/*)
		$lndir $silent $2 >&2
		;;
	*)
		$lndir $silent ../$2 >&2
		;;
	esac
	)
}

extractDirname()
{
	local dirname=$(basename $1)
	case $dirname in
	*.dif)
		echo ${dirname%.dif}
		;;
	*.diff)
		echo ${dirname%.diff}
		;;
	*.patch)
		echo ${dirname%.patch}
		;;
	*)
		echo $dirname
		;;
	esac
}

TEMP=$(/usr/bin/getopt -l 'args:,help,source:,verbose:' -o 'a:hv' -- "$@")

eval set -- "$TEMP"

srctree="linux"
patch="patch"
lndir="lndir"
patchargs="-p1 -s -E"
verbose=0
while true
do
	case "$1" in
	--args|-a)
		patchargs="$2"
		shift 2
		;;
	--help|-h)
		usage
		exit 0;;
	--source)
		srctree="$(basename $2)"
		shift 2
		;;
	-v)
		verbose=1
		shift
		;;
	--verbose)
		verbose="$2"
		shift 2
		;;
	--)
		shift
		break
		;;
	*)
		usage
		exit 1
		;;
	esac
done

patches="$@"
if [ -z "$patches" ]
then
	usage
	exit 1
fi

for tt in $patches
do
	dirname="$(extractDirname $tt)"
	createTree $dirname $srctree
	if ! applyPatch $tt $dirname
	then
		exit 1
	fi
	srctree="$dirname"
done
