#!/bin/sh

IF_FILE=/etc/network/interfaces
DEV_FILE=/var/cicada/dev_interfaces

IFUP=/sbin/ifup
IFDOWN=/sbin/ifdown


case "$1" in
        start)
                if [ -f /etc/hostname ]; then
                        hostname `cat /etc/hostname` >/dev/null 2>&1
                fi

                if [ -f $DEV_FILE ]; then
                        # this is necessary in case someone has
                        # "iface usb0 ..." in their dev_interfaces file
                        # to avoid ifup complaining about a duplicate interface
                        IFACE_USB0='^iface usb0'
                        if grep -e "$IFACE_USB0" $DEV_FILE > /dev/null ; then
                                mv $IF_FILE $IF_FILE.tmp
                                grep -v -e "$IFACE_USB0" $IF_FILE.tmp > $IF_FILE
                                rm $IF_FILE.tmp
                        fi
                        IFACE_ETH0='^iface eth0'
                        if grep -e "$IFACE_ETH0" $DEV_FILE > /dev/null; then
                                mv $IF_FILE $IF_FILE.tmp
                                grep -v -e "$IFACE_ETH0" $IF_FILE.tmp > $IF_FILE
                                rm $IF_FILE.tmp
                        fi
                        cat $DEV_FILE >> $IF_FILE 2>/dev/null
                fi

                echo -n "Configuring network interfaces: "
                #$IFDOWN -a
                if $IFUP -a; then
                        echo "done"
                else
                        echo "failed"
                        exit 1
                fi

                ifplugd -f -I -M -d 0 -i eth0
                ifplugd -f -I -M -d 0 -u 1 -i usb0
        ;;
        stop)
                $IFDOWN -a
        ;;
        *)
        ;;
esac
