#!/bin/bash
# Installs speakup to kernel sources
# Usage: ./install <KERNELDIR>

LOGFILE=install.log

log() {
	echo $* | tee -a $LOGFILE
}

die() {
 	log $* 
 	exit 1
}

apply() {
	log "Applying $1 to $2"
	patch -p 1 -l -N -i "$1" -b -z .orig -d "$2" | tee -a $LOGFILE
	if [ $? -gt 0 ];then
		die "Unable to apply $1 to $2"
	fi
}

check_kdir() {
	if [ ! -d "$1" ]; then
		die "$1 is not a directory"
	fi
	if [ ! -e "$1"/MAINTAINERS ]; then
		die "$1 is not a kernel directory"
	fi
}

get_kv() {
	VERSION=`grep "^VERSION[ 	]*=" "$1"/Makefile | awk '{print $3}'`
	PATCHLEVEL=`grep "^PATCHLEVEL[ 	]*=" "$1"/Makefile | awk '{print $3}'`
	SUBLEVEL=`grep "^SUBLEVEL[ 	]*=" "$1"/Makefile | awk '{print $3}'`
}

set -o pipefail
KDIR=${1:-/usr/src/linux}
SPKDIR="$(readlink -f "$(dirname "$0")")"

check_kdir "${KDIR}"
get_kv "${KDIR}"

if [ $VERSION -lt 2 -o $PATCHLEVEL -lt 6 -o $SUBLEVEL -lt 18 ]; then
	die "Speakup does not support kernels before 2.6.18."
fi

if [ $SUBLEVEL -lt 26 ]; then
	BLDPATCH="$SPKDIR/patches/kernel-integration-2.6.24-build.patch"
	SRCDIR="${KDIR}/drivers/char/speakup"
else
	BLDPATCH="$SPKDIR/patches/kernel-integration-2.6.26-build.patch"
	SRCDIR="${KDIR}/drivers/accessibility/speakup"
fi

if [ $SUBLEVEL -le 18 ]; then
	SRCPATCH="$SPKDIR/patches/notifier-integration-2.6.18-and-below.patch"
elif [ $SUBLEVEL -ge 19 -a $SUBLEVEL -le 21 ]; then
	SRCPATCH="$SPKDIR/patches/notifier-integration-2.6.21-and-below.patch"
elif [ $SUBLEVEL -ge 22 -a $SUBLEVEL -le 23 ]; then
	SRCPATCH="$SPKDIR/patches/notifier-integration.patch"
elif [ $SUBLEVEL -ge 24 -a $SUBLEVEL -le 25 ]; then
	SRCPATCH="$SPKDIR/patches/kernel-integration-2.6.24-source.patch"
else
	SRCPATCH="none"
fi

if [ -d "${SRCDIR}" ]; then
	log It appears that speakup is already installed into this kernel.
	die Please start with a fresh kernel tree.
fi

if [ "${BLDPATCH}" != "none" ]; then
	apply "${BLDPATCH}" "${KDIR}"
fi

if [ "${SRCPATCH}" != "none" ]; then
	apply "${SRCPATCH}" "${KDIR}"
fi

log Installing user documentation.
cp -a "${SPKDIR}/doc" "${KDIR}/Documentation/speakup"
log Installing speakup source.
cp -a "${SPKDIR}/src" "${SRCDIR}"
log Speakup has been installed to ${KDIR}
