#!/bin/bash
# Script that automatically applies patches.

paths=
patches=

while [ $# -gt 0 ]; do
	case "${1}" in
		--search-path=*)
			paths="${paths} ${1#--search-path=}"
			;;
		*)
			patches="${patches} ${1}"
			;;
	esac
	shift
done

if [ -n "${patches}" ]; then
	echo "Applying patches..."
fi

# Apply all patches given on command line.
for patch in ${patches}; do
	case "${patch}" in
		/*)
			;;
		*)
			for path in ${paths}; do
				if [ -e "${path}/${patch}" ]; then
					patch="${path}/${patch}"
					break
				fi
			done
			;;
	esac

	# Check if patch file does exist.
	if ! [ -e "${patch}" ]; then
		echo >&2 "  ERROR: Patch file does not exist: ${patch}"
		exit 1
	fi

	# Options applied to patch command.
	options="-N"

	# Get right -p1 option.
	case "${patch}" in
		*.patch[0-9]|*.patch[0-9]R)
			_patch="${patch}"
			# Get patch level from file name.
			while [ ${#_patch} -gt 0 ]; do
				last_pos=$(( ${#_patch} - 1 ))
				last_char=${_patch:${last_pos}}
				_patch=${_patch:0:${last_pos}}

				case "${last_char}" in
					[0-9])
						options="${options} -p${last_char}"
						break
						;;
					R)
						options="${options} -R"
						;;
				esac
			done
			;;
		*.patch|*.diff)
			# Default is -p1.
			options="${options} -p1"
			;;
		*)
			echo >&2 "   WARNING: Ignoring unknown file: ${patch}"
			continue
			;;
	esac

	echo "  Applying ${patch} (${options})..."
	patch ${options} -i ${patch} || exit $?
done

exit 0
