#!/bin/sh

# Call this script to apply all patches. 
#
# A patch is a directory containing at least a script named patch.sh. 
# A directory containing a patch must start with three numerical characters 
# and a '_'-character, e.g. 012_MyPatch
#
# Patches will be applied in numerical order, starting from 000_*. 

THIS_DIR=$(dirname "$0")

# What to do: check if any patch is needed or actually applying them...
ACTION=$1

if [ "$ACTION" != "check" ] && [  "$ACTION" != "execute" ];
then
	echo "Unkonwn switch '$ACTION', only 'check' or 'execute' allowed"
	exit 0
fi

numAppliedPatches=0
patchNeeded=0

# Apply pathces
for patchDir in $THIS_DIR/[0-9][0-9][0-9]_* ; 
do
	if [ -d "$patchDir" ];
	then
		subScript="$patchDir/patch.sh"
		if [ -e "$subScript" ];
		then
			if [ "$ACTION" == "check" ]; 
			then
				sh $subScript $ACTION
				if [ "$?" -eq 1 ]; 
				then
					logger "At least one patch needs to be applied"
					exit 1
				fi					
			else
				logger "Applying patch '$subScript'"
				sh $subScript $ACTION
				numAppliedPatches=$((numAppliedPatches + 1))
			fi
			
		fi		
	fi	
done

# Print some result
if [ "$ACTION" != "execute" ];
then
	if [ "$numAppliedPatches" -eq 0 ]; 
	then
		logger "No patches to apply"
	else
		logger "$numAppliedPatches patch were applied"
	fi
fi

exit 0