#!/bin/sh
#
# setup the network
#
# runlevels: geexbox, debug

echo "### Setting up network ###"

# get options
test -f /etc/network || exit 1
. /etc/network
test -z "$HOST" && HOST=0.0.0.0
if [ -x /usr/bin/iwconfig ]; then
  for i in `iwconfig 2>&1 | grep '^[^\ ]' | grep -v '^lo' | cut -f1 -d' '`; do
    ifconfig $i up >/dev/null 2>&1
  done
  WIFI=`iwconfig 2>&1 | grep '^[^\ ]' | grep -v "no wireless extensions" | cut -f1 -d' ' | head -n 1`
  ETH=`iwconfig 2>&1 | grep '^[^\ ]'  | grep -v '^lo' | grep "no wireless extensions" | cut -f1 -d' ' | head -n 1`
else
  ETH=eth0
fi

# select device
if test $PHY_TYPE = wifi -o $PHY_TYPE = auto; then
  DEV=$WIFI
  if test -n "$DEV"; then
    test -n "$WIFI_MODE" && iwconfig "$DEV" mode "$WIFI_MODE"
    test -n "$WIFI_ESSID" && iwconfig "$DEV" essid "$WIFI_ESSID"
    test -n "$WIFI_WEP" && iwconfig "$DEV" key "$WIFI_WEP"
  fi
fi
if test $PHY_TYPE = ethernet -o $PHY_TYPE = auto -a -z "$DEV"; then
  DEV=$ETH
fi
test -n "$DEV" || exit 1

[ -n "$SUBNET" ] && NETMASK="netmask $SUBNET"

# bring interface up
if ifconfig $DEV $HOST $NETMASK >/dev/null 2>&1; then
  if test $HOST = 0.0.0.0; then
    udhcpc -H geexbox -n -i $DEV >/dev/null 2>&1 && NET=yes
    test "$NET" != yes && ifconfig $DEV 192.168.0.54 netmask 255.255.255.0 && NET=yes
  else
    metric=0
    for i in $GATEWAY; do
      route add default gw $i dev $DEV metric $((metric++))
    done
    NET=yes
  fi
fi

if test "$UPNP" = "yes"; then
  # bring lo up and add UPnP multicast route
  ifconfig lo 127.0.0.1
  route add -net 239.0.0.0 netmask 255.0.0.0 $DEV
fi

# adding DNS server
if [ "$NET" = yes ]; then
  for i in $DNS_SERVER; do
    echo "nameserver $i" >> /etc/resolv.conf
  done
fi

test "$NET" = yes || exit 1

exit 0
