#!/bin/sh
# chkconfig: 2345 70 30
### BEGIN INIT INFO
# Provides:          detect-mouse
# Required-Start:    modules
# Required-Stop:     modules
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Detect mouse device at boot time
# Description:       Search SysFs data to discover standard mouse device, 
#   and document the mouse location
# X-Start-Before:    x
# X-Stop-After:      
# X-Timesys-Start-Number:  70
# X-Timesys-Stop-Number:  30
### END INIT INFO

# discover mouse device at boot
PATH=/usr/bin:/bin:/usr/sbin:/sbin
export HOME=/root
MOUSEDEV=

# Given an event name, find it in the /dev tree.
# This accounts for differences between mdev and udev
scan_dev ()
{
    SHORTDEV=$1

    if [ -z "$SHORTDEV" ]; then
       MOUSEDEV=
       return 1
    elif [ -e /dev/$SHORTDEV ]; then
       MOUSEDEV=/dev/$SHORTDEV
    elif [ -e /dev/input/$SHORTDEV ]; then
       MOUSEDEV=/dev/input/$SHORTDEV
    else
       MOUSEDEV=
       return 1
    fi

    return 0
}

find_mouse ()
{
    SYSDIR=/sys/class/input

    # Check the capabilities of the input devices
    for DEV in $SYSDIR/input*; do
       CAPDIR=$DEV/capabilities
       ABS=`cat $CAPDIR/abs`
       REL=`cat $CAPDIR/rel`
       KEY=`awk '{print $1}' $CAPDIR/key`
       if [ $ABS -eq 0 ] && [ $REL -ne 0 ] && [ $KEY -ne 0 ]; then
             SHORTDEV=`basename $DEV | sed s/input/event/`
             break
       fi
    done

    scan_dev $SHORTDEV
    return $?
}

find_device ()
{
    echo -n "Finding mouse"

    if [ -z $MOUSEDEV ]; then
       find_mouse
    fi

    echo -n ":"

    if [ $MOUSEDEV ]; then
      echo -ne " $MOUSEDEV "
      echo $MOUSEDEV > /etc/mouse.dev
      echo '[ OK ]'
    else
      rm -f /etc/mouse.dev
      echo '[FAIL]'
      exit 1
    fi
}

case "$1" in
    start)
        find_device
    ;;
    stop)
    ;;
    *)
        $0 start
    ;;
esac
