#!/bin/bash
if [ "$1" = "ATTACH" ]; then
	if [ -f /proc/bus/input/devices ]; then
		INPUTPATH=`grep -A2 Sundtek /proc/bus/input/devices | grep Sysfs | sed 's#.*Sysfs=#/sys#g'`

		if [ "$INPUTPATH" = "" ]; then
			echo "RC: no remote attached"
			exit 0;
		fi

		EVENT=`ls ${INPUTPATH}/event* -d | sed 's#.*event##g'`

		EVENTFILE=/dev/input/event${EVENT}
		if [ "$EVENTFILE" = "/dev/input/event" ]; then
			echo "RC: no remote attached"
			exit 0;
		fi
		if [ -c $EVENTFILE ]; then
			echo `date +"%Y-%m-%d %H:%M:%S [$$]"`" RC: IR Event /dev/input/event${EVENT}" >> /var/log/mediasrv.log
		fi

		if [ -f /etc/lirc/hardware.conf ]; then
		        if [ `grep REMOTE_DRIVER /etc/lirc/hardware.conf | grep devinput -c` -eq 0 ]; then
				sed -i 's/REMOTE_DRIVER.*/REMOTE_DRIVER="devinput"/g' /etc/lirc/hardware.conf
			fi
			sed -i "s#REMOTE_DEVICE=.*#REMOTE_DEVICE=/dev/input/event${EVENT}#" /etc/lirc/hardware.conf
			if [ -f /etc/init.d/lirc ]; then
				echo `date +"%Y-%m-%d %H:%M:%S [$$]"`" RC: Restarting LIRC" >> /var/log/mediasrv.log
				/etc/init.d/lirc restart 
			fi
		fi
	fi
elif [ "$1" = "REMOVE" ]; then
	echo `date +"%Y-%m-%d %H:%M:%S [$$]"`" RC: detached remote control" >> /var/log/mediasrv.log
else
	echo "Syntax: $0 [ATTACH|REMOVE]"
fi
