#! /bin/bash

#location of driver has changed >= 2.6.22
LIVECD_FILE=.livecd
[ -f "$LIVECD_FILE" ] && rm $LIVECD_FILE

if [ -d "/lib/modules/`uname -r`/kernel/drivers/usb/input" ]; then
	DRV_LOC=/lib/modules/`uname -r`/kernel/drivers/usb/input
elif [ -d "/lib/modules/`uname -r`/kernel/drivers/input/tablet" ]; then
	DRV_LOC=/lib/modules/`uname -r`/kernel/drivers/input/tablet
elif [ -d "/lib/modules/`uname -r`/kernel/drivers/usb" ]; then
	DRV_LOC=/lib/modules/`uname -r`/kernel/drivers/usb
else
	echo Promethean: Error finding correct driver location !
	# Usually when we build the live cd. It will be done later anyway.
	touch $LIVECD_FILE
	exit 0
fi

echo Driver location: $DRV_LOC

BUILD=0
INSTALL=1
MOD_FILE=promethean.ko

if [ "$1" == "install" ]; then
	echo "Promethean: Copying driver module in kernel."
	INSTALL=1
	/sbin/rmmod promethean
	cp ./$MOD_FILE $DRV_LOC && /sbin/depmod -a && /sbin/modprobe -v promethean

	if [ $? -ne 0 ]; then
		echo "Promethean: No driver found for the current kernel `uname -r`. The driver needs to be rebuilt."
		echo "Promethean: This requires make, gcc and the kernel headers / kernel source packages."
		BUILD=1
		rm $DRV_LOC/$MOD_FILE
		# in case date is in the past on target computer
		cp ./$MOD_FILE ./$MOD_FILE.backup
		rm ./$MOD_FILE
		touch *
	fi
elif [ "$1" == "noinstall" ]; then
	BUILD=1
	INSTALL=0
else
	BUILD=1
fi

if [ $BUILD -eq 1 ]; then
	echo Promethean: Building Promethean activdriver...

	BUILT=0
	make clean
	(make &> build.log) && BUILT=1
	logger -f build.log
	
	if [ $BUILT -eq 1 ]; then
		if [ $INSTALL -eq 1 ]; then
			echo Installing...
			/sbin/rmmod promethean
			cp ./$MOD_FILE $DRV_LOC && /sbin/depmod -a && /sbin/modprobe -v promethean && echo Driver installed successfully
			rm ./$MOD_FILE.backup
		fi
	else
		echo "Promethean: Error building driver."
	fi
fi

# [ -f "$MOD_FILE.backup" ] && cp $MOD_FILE.backup $MOD_FILE
