#!/bin/bash

set -e

PD=$PWD/patches

apply_patch() {
patches="$(readlink -f -- $1)"
tree="$2"

for project in $(cd $patches/patches/$tree; echo *);do
	p="$(tr _ / <<<$project |sed -e 's;platform/;;g')"
	pushd $p
	git clean -fdx; git reset --hard
		for patch in $patches/$project/*.patch;do
		if git apply --check $patch;then
			git am $patch
		elif patch -f -p1 --dry-run < $patch > /dev/null;then
			#This will fail
			git am $patch || true
			patch -f -p1 < $patch
			git add -u
			git am --continue
		else
			echo "Failed applying $patch"
			exit 1
		fi
		done
		popd
	done
}

if [ $1 = leos ];then
echo ""
echo "Adapt LeOS"
echo "Executing in 5 seconds - CTRL-C to exit"
echo ""
fi


echo "Applying patches"
apply_patch $PD $1
