#!/bin/sh
#
# Start the network....
#

# Default IP addresses
EIP=192.168.1.7
WIP=192.168.1.8

case "$1" in
  start)
    echo "Starting network..."
    /sbin/ifup -a

    /sbin/ifconfig eth0 >/dev/null 2>&1
    rcE0=$?
    rcE1=1
    if [ $rcE0 -eq 0 ] 
    then
        # Use DHCP to get an initial address, if available
        /sbin/udhcpc -t 3 -A 1 -n -q -i eth0 
        rcE1=$?
    fi

    /sbin/ifconfig wlan0 >/dev/null 2>&1
    rcW0=$?
    rcW1=1
    if [ $rcW0 -eq 0 ] 
    then
        # Enable WPA Supplicant
        wpa_supplicant -B -c /etc/wpa_supplicant.conf -Dnl80211 -iwlan0
        # Ugly, but this can take awhile to complete
        sleep 10

        # Use DHCP to get an initial address, if available
        /sbin/udhcpc -t 3 -A 1 -n -q -i wlan0 
        rcW1=$?
    fi
    
    # If not available, use config file or defaults
    if [ $rcE1 -eq 1 ] && [ $rcW1 -eq 1 ]
    then
        if [ $rcE0 -eq 0 ]
        then
            echo "Using default IP address $EIP for eth0"
            /sbin/ifconfig eth0 $EIP
            /sbin/ifconfig eth0 up
        fi
        if [ $rcW0 -eq 0 ]
        then
            echo "Using default IP address $WIP for wlan0"
            /sbin/ifconfig wlan0 $WIP
            /sbin/ifconfig wlan0 up
        fi
    fi
    ;;

  stop)
    echo "Stopping network..."
    killall wpa_supplicant
    /sbin/ifdown -a
    /sbin/ifconfig wlan0 >/dev/null 2>&1
    rc=$?
    if [ $rc -eq 0 ] 
    then
        /sbin/ifconfig wlan0 down 
    fi
    /sbin/ifconfig eth0 >/dev/null 2>&1
    rc=$?
    if [ $rc -eq 0 ] 
    then
        /sbin/ifconfig eth0 down 
    fi
    ;;

  restart|reload)
    "$0" stop
    "$0" start
    ;;

  *)
    echo $"Usage: $0 {start|stop|restart}"
    exit 1
esac

exit $?

