#!/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])
			# Get patch level from file name.
			level=${patch:$(( ${#patch} - 1))}
			options="${options} -p${level}"
			;;
		*.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
