#!/bin/bash

VERSION=v`head -2 /usr/src/linux/Makefile | \
	awk '{ printf "%s",$3 }'`

DIR=/usr/src/linux/drivers/char/speakup

echo "Patching version $VERSION"

if [ "$1" != "--debug" ]; then
	SILENT=--silent
fi

cp -R speakup /usr/src/linux/drivers/char/

#  make .orig files
echo -n 'Creating .orig files ['
for i in `cat ${DIR}/patchlist-${VERSION}`; do
	patch=`echo $i | cut -f 1 -d ,`
	filebase=`echo $i | cut -f 2 -d ,`

	mkdir -p `dirname $filebase`
	if [ "$patch" == "1" ]; then
		if [ ! -e $filebase.orig ]; then
			echo -n .
			cp $filebase $filebase.orig
		fi
	fi
done
echo '] done.'

#  apply patches
echo -n 'Patching files ['
for i in ${DIR}/diff-${VERSION}/*.patch; do
	# skip dirs
	[ -d $i ] && continue
	echo -n p
	writeloc=${i##$DIR\/diff-${VERSION}\/}
	writeloc=${writeloc%.patch}
	writeloc=${writeloc//^/\/} 
	patch $SILENT -f -p0 -o $writeloc $writeloc.orig $i
done
echo '] done.'

#  copy files
echo -n 'Copying files ['
for i in ${DIR}/diff-${VERSION}/*.copy; do
	# skip dirs
	[ -d $i ] && continue
	echo -n c
	writeloc=${i##$DIR\/diff-${VERSION}\/}
	writeloc=${writeloc%.copy}
	writeloc=${writeloc//^/\/} 
	cp $i $writeloc
done
echo '] done.'
