#!/bin/sh
# This shell script takes care of inserting and removing
# dLAN USB network driver 
#           
# Copyright 2007 devolo AG
#

DRIVER=devolo_usb

usbmgr(){
    test -f /proc/cpuinfo || mount -n -t proc proc /proc
    if test -x /sbin/lspci; then
    USB_PCI="/sbin/lspci -v"
    elif test -x /bin/lspci; then
	USB_PCI="/bin/lspci -v"
    elif test -x /usr/sbin/lspci; then
	USB_PCI="/usr/sbin/lspci -v"
    elif test -x /usr/bin/lspci; then
	USB_PCI="/usr/bin/lspci -v"
    else
	test -e /proc/pci && USB_PCI="cat /proc/pci"
    fi
    
    echo "USB determination method: $USB_PCI"
    USB_HCI=`
	eval $USB_PCI |
	while read line ; do
		case "$line" in
		*UHCI*) echo "uhci"; break ;;
		*OHCI*) echo "ohci"; break ;;
#		*USB*Intel*|*USB*VIA*) echo "usb-uhci"; break ;;
#		*USB*)                 echo "usb-ohci"; break ;;
		esac
	done`
    if test -z "$USB_HCI"; then
	echo "No USB controller found" 
    else
	echo "USB driver to be loaded: $USB_HCI"
	modprobe "$USB_HCI" 
    fi
}


if test -f /etc/init.d/network; then
    NETSCRIPT=/etc/init.d/network
elif test -f /etc/init.d/networking ; then
    NETSCRIPT=/etc/init.d/networking
else
    NETSCRIPT="echo now probably you should manually execute network"
fi


echo_success(){ 
    echo "     OK" 
}


echo_failure(){ 
    echo "     FAILED" 
}

start(){
#    test -z `lsmod|grep usb-uhci\|usb-ohci` && usbmgr
    modprobe $DRIVER ;
    test $? -eq 0 &&  echo_success || echo_failure
    sleep 2
    
    ifaces=`grep dlanusb /proc/net/dev|cut -d: -f1`
    if [ -n "$ifaces" ]; then
	echo "executing dlan network restart ..."
	for i in $ifaces; do
	    ifup $i
	done
	# $NETSCRIPT restart
    fi
}
stop(){
    ifaces=`grep dlanusb /proc/net/dev|cut -d: -f1`
    for i in $ifaces; do
	ifconfig $i 0.0.0.0 down;
    done
    modprobe -r $DRIVER;
    test $? -eq 0 &&  echo_success || echo_failure
}

case $1 in
    start)
	start
	;;
    stop)
        stop
	;;
    restart)
	#stop
	stop
	#start
	start
	;;
    status)
	ishere=`lsmod|grep ^$DRIVER`
	if [ -n "$ishere" ]; then
	    echo "module $DRIVER is loaded"
	else
	    echo "module $DRIVER is not loaded"
	fi
	;;
    *)
	echo "Usage: $0 (start|stop|restart|status)";
	;;
    
esac

