#!/bin/bash

usage() {
	echo "Usage:  $0 [-c] [-l logfile] [kerneldir]"
	echo "c : copy (don't symlink) the source into the kernel tree."
	echo "l logfile : create install log (the default is install.log)."
	echo "[kerneldir] - the kernel tree to install to (default is /usr/src/linux)"
	exit 1
}

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

while getopts ":cl:" opt; do
	case $opt in
		c) COPY_INSTALL=1
			;;
		l) LOGFILE=$OPTARG
			;;
		*) usage
			;;
	esac
done
shift $(($OPTIND - 1))

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

if [ -z "$LOGFILE" ]; then
	LOGFILE=install.log
fi

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

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

BLDPATCH="$SPKDIR/patches/build-integration.patch"
SRCDIR="${KDIR}/drivers/accessibility/speakup"

if [ -f ${KDIR}/drivers/char/speakup ]; then
	log It appears that speakup is installed in drivers/char/speakup.
	log This is no longer the correct location for speakup.
	die Please start with a fresh kernel tree.
fi

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

if [ -n "${BLDPATCH}" ]; then
	apply "${BLDPATCH}" "${KDIR}"
fi

if [ -n "$COPY_INSTALL" ]; then
	CMD="cp -a"
else
	CMD="ln -s"
fi

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