#!/bin/bash

#loops over the X logfile, and looks for unreported scancode entries.
#It relies on recieving two message - one for key down, one for key up - and runs the command on key-up
#Occasionally, it gets confused (say you have a volume key, and hold it down)
#and sees an odd number of entries. Ouch
#So if you press another key, it gets out of sync - and realises this, so just disscards the one command. It will be back to normal if you press it again.

#It has a modifier key. Press and release the mod key, then press a special key, and it runs a second command. For Free!
#My keyboard is a logitech cordless, and the mod key is the "magnifying glass"


display=`echo -n "$DISPLAY" | sed -n 's/:\(.\)\(\..*\)/\1/p'`

if [ "$display" = "" ] ; then
	echo "not local display?"
	exit 1
fi

#tail -n 0 --retry --follow=name /var/log/XFree86.$display.log | while read a b c d e ; do
#tail -n 0 -f /var/log/XFree86.$display.log | while : ; do
mod=0
tailf /var/log/XFree86.$display.log 0 | while : ; do
	read a b c d code
	if [ "$c" = Prefix0 ] ; then
		read a b c d code1
		if [ "$code1" != "$code" ] ; then
			echo "Seems to be some kinda error in sync. Discarding one keypress on `date`"
                        beep
			read a
			continue
		fi
		

        #look at modifier keys first!
                case "$code" in
                    0x65)	
			if [ "$mod" = 1 ] ; then  #bump up "modifiedness"
				mod=2
                        elif [ "$mod" = 2 ] ; then
                                mod=0
			else
				mod=1
			fi
                        continue
                    ;;
                esac

		/usr/local/bin/speckeys/runtesttconnors "$code" "$mod" &
                mod=0    #reset modness after running a commmand
	fi
done 

#echo "WTF"
#exec $0
