#!/bin/bash

if ps -e | grep -qe "X\|kdm"; then
	echo "X must not be running while loading the ibmasm driver"
	echo "Kill X and try again."
	exit 1
fi

if grep -v -q ibmasmfs /proc/filesystems; then
	modprobe ibmasm || exit 1
fi

echo -en "\nWaiting for ibmasm device to appear "
TIMEOUT=10
for ((i=0; i<$TIMEOUT; i++)); do
	DEVICE=`evnode -n "ibmasm RSA I remote mouse"`
	if [ ! -z $DEVICE ]; then break; fi
	echo -n ". "
	sleep 1
done
echo
DEVICE=`evnode -n "ibmasm RSA I remote mouse"`
XCONFIG="/etc/X11/XF86Config"
if [ -e $XCONFIG ]; then
	TMPFILE=`mktemp /tmp/ibmspupX.XXXXXXXXXX` || exit 1
	AWKFILE=`mktemp /tmp/ibmspupAWK.XXXXXXXXXX` || exit 1
	cat > $AWKFILE <<-ENDAWK
	BEGIN{
	        RS=""
	        found_ibmasm=0
	        started_input=0
	}
	{
	        if (\$1=="Section" && index(\$2, "InputDevice") != 0 && found_ibmasm == 0) {
	                started_input = 1
	                if (found_ibmasm == 0 && \$0 ~ /Identifier[ \t]*"ibmasm_remote"/) {
	                        sub(/Option[\t ]*"Device"[\t ]*"[^"]*"/,"Option       \"Device\" \"$DEVICE\"", \$0)
	                        found_ibmasm = 1
	                }
	        } else if (\$1 == "Section" && index(\$2, "ServerLayout") != 0) {
	                if (index(\$0, "ibmasm_remote") == 0) {
	                        sub(/[ \t]*Screen/, "  InputDevice  \"ibmasm_remote\"\n&", \$0)
	                }
	        } else if (started_input == 1 && found_ibmasm == 0) {
	                print "Section \"InputDevice\""
	                print "  Driver       \"ibmasm\""
	                print "  Identifier   \"ibmasm_remote\""
	                print "  Option       \"Device\" \"$DEVICE\""
	                print "  Option       \"XScale\" \"1024\""
	                print "  Option       \"YScale\" \"768\""
	                print "  Option       \"SendCoreEvents\" \"True\""
	                print "EndSection\n"
	                found_ibmasm = 1
	        }
	        printf "%s\n\n", \$0
	}
	ENDAWK
	awk -f $AWKFILE $XCONFIG > $TMPFILE 
	mv $XCONFIG ${XCONFIG}.ibmspupsave
	mv $TMPFILE $XCONFIG
	rm -f $AWKFILE
fi

mount -t ibmasmfs ibmasm /var/lib/ibmasm

/sbin/ibmsphalt > /dev/null 2>&1 &
