#!/bin/sh

source ${CONF_DIR}/config
source ${CONF_DIR}/helpers/functions

INET_IF="eth0";
HELPERS_DIR="/etc/sysconfig/helpers";

# We start the network only if enable
if [ "X${CONFIG_NETWORK_ENABLE}" != "Xy" ]; then
	echo -ne "ERROR:\nNetwork not enabled in this configuration.";
	exit 1;
fi

if [ "X$1" == "Xstart" ]; then

	# Retrieve MAC address
	MAC_ADDR="$(${HELPERS_DIR}/boardcfg ethaddr)";
	if [ -z "${MAC_ADDR}" ]; then
		echo -ne "ERROR:\nFailed to get MAC address.";
		exit 10;
	fi	

	# Start the network
	load_module dw_stmmac ${CONFIG_CHKCONFIG_NETWORK_MODPARAMS}
	if [ $? -ne 0 ]; then
		echo -ne "ERROR:\nFailed to start network driver.";
		exit 20;
	fi

	load_module af_packet
	if [ $? -ne 0 ]; then
		echo -ne "ERROR:\nFailed to start IP driver.";
		exit 30;
	fi

	ifconfig eth0 hw ether ${MAC_ADDR}
	# Get an IP address, supported modes are static and DHCP
	if [ "X${CONFIG_NETWORK_IPADDR_DYNAMIC}" == "Xy" ]; then
		/sbin/udhcpc --interface=${INET_IF} --now;
		if [ "X$?" != "X0" ]; then 
			echo -ne "ERROR:\nFailed to start the network on ${INET_IF} using DHCP."; 
			exit 40;
		fi
	else
		IP_ADDR="$(${HELPERS_DIR}/boardcfg ipaddr)";
		/sbin/ifconfig ${INET_IF} ${IP_ADDR} ${CONFIG_CHKCONFIG_NETWORK_IFCONFIG_OPTIONS} up
		if [ "X$?" != "X0" ]; then 
			echo -ne "ERROR:\nFailed to start the network on ${INET_IF} using IP ${IPADDR}"; 
			exit 45;
		fi
	fi

	if [ "X${CONFIG_NETWORK_GATEWAY_IPADDR}" != "X" ]
	then
		/bin/busybox route add default gw ${CONFIG_NETWORK_GATEWAY_IPADDR}
	fi

elif [ "X$1" == "Xstop" ]
then
	/usr/bin/killall udhcpc
	/sbin/ifconfig ${INET_IF} down;
	/sbin/modprobe -q -r dw_stmmac
fi

exit 0;
