#!/bin/bash

usage() {
	echo "Usage:  $0 [-c] [-l logfile] [-s] [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 "-s : install into kernel staging directory"
	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:s" opt; do
	case $opt in
		c) COPY_INSTALL=1
			;;
		l) LOGFILE=$OPTARG
			;;
		s) STAGING_INSTALL=1
			COPY_INSTALL=1
			;;
		*) 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

if [ -z "$STAGING_INSTALL" ]; then
	BLDPATCH="$SPKDIR/patches/build-integration.patch"
	DOCDIR="${KDIR}/Documentation/speakup"
	SRCDIR="${KDIR}/drivers/accessibility/speakup"
else
	BLDPATCH="$SPKDIR/patches/staging-integration.patch"
	DOCDIR="${KDIR}/drivers/staging/speakup"
	SRCDIR="${KDIR}/drivers/staging/speakup"
fi

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

if [ -n "$STAGING_INSTALL" -a ! -d ${KDIR}/.git ]; then
	die staging installs should be done with the kernel git tree.
fi

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

log Installing user documentation.
if [ -z "${COPY_INSTALL}" ]; then
	ln -s "${SPKDIR}/doc" "${DOCDIR}"
else
	if [ ! -d "${DOCDIR}" ]; then
		mkdir "${DOCDIR}"
	fi
	cp -a "${SPKDIR}"/doc/* "${DOCDIR}"
fi

log Installing speakup source.
if [ -z "$COPY_INSTALL" ]; then
	ln -s "${SPKDIR}/src" "${SRCDIR}"
else
	if [ ! -d "${SRCDIR}" ]; then
		mkdir "${SRCDIR}"
	fi
	cp -a "${SPKDIR}"/src/* "${SRCDIR}"
fi

if [ -n "${STAGING_INSTALL}" ]; then
	mv "${SRCDIR}/Kbuild" "${SRCDIR}/Makefile"
	rm "${SRCDIR}/allmodule.mk"
	cp "${SPKDIR}"/TODO.staging ${DOCDIR}/TODO
fi

log Speakup has been installed to ${KDIR}
