#!/bin/bash

cd /sys/bus/pnp/devices

IRDA=0;
STATEFILE=/var/run/irdadev;

for x in *; do
    FIR="false";
    SIR="false";
    FALLBACK=true;
    OPTIONS=0;
    for y in `cat $x/id`; do
	case "$y" in
	    PNP0510|PNP0511)
	    SIR="true";
	    ;;
	    NSC*)
	    FIR="nsc-ircc";
	    ;;
	    IBM0071)
	    FIR="nsc-ircc";
	    OPTIONS="dongle_id=0x09";
	    ;;
	    SMC*)
	    FIR="smsc-ircc2";
	    ;;	    
	esac
    done
    
    # Work out resource ranges, so we know which serial port to work with
    PORT=`grep io $x/resources | sed -e 's/io \(.*\)-.*/\1/'`
    case $PORT in
	0x3f8)
	PORT="/dev/ttyS0"
	;;
	0x2f8)
	PORT="/dev/ttyS1"
	;;
	0x3e8)
	PORT="/dev/ttyS2"
	;;
	0x2e8)
	PORT="/dev/ttyS3"
	;;
	default)
	PORT="UNKNOWN"
	;;
    esac;
    

    if [ "$FIR" != "false" ]; then
	UART="unknown";
	if [ "$PORT" != "UNKNOWN" ]; then
	    # We should attempt to disable the UART. However, we need to store
	    # it - there's a chance that things could still go horribly wrong
	    UART=`setserial $PORT | sed 's/.*UART: \(.*\), Port.*/\1/'`
	    setserial $PORT uart none
	fi
	modprobe $FIR $OPTIONS;
	if [ "$?" = "0" ]; then
	    echo "irda$IRDA fir" >$STATEFILE;
	    let "IRDA=$IRDA+1";
	    FALLBACK=false;
	else
	    # Try to recover
	    setserial $PORT uart $UART;
	fi
    fi

    if [ "$SIR" = "true" ]; then
	if [ "$FIR" = "false" -o "$FALLBACK" = "true" ]; then
	    # Ok, let's try just driving the UART
	    # The IRQ is not always set correctly, so try to deal with that
	    IRQ=`grep irq $x/resources | sed -e 's/irq \(.*\)/\1/'`
	    setserial $PORT irq $IRQ;
	    echo "$PORT sir" >$STATEFILE;
	fi
    fi
done
