#!/bin/bash
#
#     Template Copyright (C) 1995--2005  Kurt Garloff, SUSE / Novell Inc.
#	Licensed under GPL.
#          
# Loads the keytable for the infrared remote control.  
# Author: Jim Carter <jimc@math.ucla.edu> , 2012-04-08
#
### BEGIN INIT INFO
# Provides:          ir-remoteJ
# Required-Start:    
# Should-Start:      
# Required-Stop:     
# Should-Stop:       
# Default-Start:     2 3 5
# Default-Stop:      0 1 6
# Short-Description: Loads the keytable for the infrared remote control.
# Description:       Loads the keytable for the infrared remote control
#	so button scancodes can feed into the event 
#	subsystem, and from there to the X-Windows 
#	keyboard clickstream.
### END INIT INFO

# WARNING, contains bash-isms.  Debian policy requires all startup scripts
# to work with any POSIX shell.  

# The keytable should be configured in /etc/sysconfig/something, but I'm too
# lazy to do that.
KEYTAB=/etc/rc_keymaps/rc6_mce
# The protocol may be a comma-separated list.  Use ir-keytable without
# arguments to see a list of available protocols.  Actually this is not used;
# when the keytable is loaded the protocol is set as it specifies.  
PROTO=RC-6

IRT_BIN=/usr/bin/ir-keytable
test -x $IRT_BIN || { echo "$IRT_BIN not installed"; 
	if [ "$1" = "stop" ]; then exit 0;
	else exit 5; fi; }

# Sets global variable IRT to the system basename of the (first) remote
# control, e.g. rc0.  It returns nonzero if no remote controls were found. 
# Also fails if $KEYTAB does not exist.  
function getirt () {
    shopt -s nullglob
    local irts=(`echo /sys/class/rc/*`)
    IRT=${irts[0]##*/}
    if [ ! -r $KEYTAB ] ; then
	echo -n "(Missing $KEYTAB) "
	irts=()
    fi
    [ ${#irts[*]} -gt 0 ]
}

# SuSE/LSB init script functions
. /etc/rc.status

# Reset status of this service
rc_reset

case "$1" in
    start | try-restart | condrestart | restart | force-reload | reload )
	echo -n "Loading remote control keytable "
	if getirt ; then
	    $IRT_BIN -s $IRT -c 2> /dev/null
	    $IRT_BIN -s $IRT -w $KEYTAB 2> /dev/null
	    rc_status -v
	else
	    rc_status -u
	fi
	;;
    stop)
	echo -n "Clearing remote control keytable "
	if getirt ; then
	    $IRT_BIN -s $IRT -c 2> /dev/null
	    rc_status -v
	else
	    rc_status -u
	fi
	;;
    status)
	# This checks if some keytable is loaded (vs. none), not whether
	# it is the correct one.  
	echo -n "Checking on remote control keytable "
	if getirt ; then
	    $IRT_BIN -s $IRT -r 2> /dev/null | grep -i scancode > /dev/null
	    rc_status -v
	else
	    rc_status -u
	fi
	;;
    *)
	echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}"
	exit 1
	;;
esac
rc_exit
