#!/bin/bash 

TMP=`tempfile`
STATE=/var/run/irda.discovery
MODULES="ircomm-tty ircomm nsc-ircc irda"

# If IRDA is operational
if [ -d /proc/net/irda -a -f /proc/net/irda/irlmp ]; then

	cat /proc/net/irda/irlmp | \
		sed -ne '/^Connected/,$p' |\
		grep lsap \
		>$TMP

	# compare with last check
	cmp -s $TMP $STATE

	# if we have a change - copy file
	if [ $? -ne 0 ]; then
		mv $TMP $STATE
		exit
	fi

	# Do we have a device in range ?
	if [ -s $STATE ]; then
		exit
	fi

	# we do not have any device in range but how
	# long does this state last ?
	if [ ! -z "`find $STATE -mmin +5`" ]; then

		echo Removing irda modules due to inactivity | logger

		# Disable device
		ifconfig irda0 down

		# Remove modules
		for i in $MODULES; do
			if [ ! -z "`lsmod | egrep ^$i`" ]; then
				rmmod $i 
				# if we fail to unload any module - bomb out
				if [ $? -ne 0 ]; then
					exit
				fi
			fi
		done

		# Remove state
		rm -f $STATE
		exit
	fi
fi
