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

me=[S16network]
IFACE=br0

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars

log() {
	LOGGER=$(which logger)
	if [ "${LOGGER}" != "" ]; then
		${LOGGER} -t "${me}" "$1"
		echo "$1"
	else
		echo "$1"
	fi
}

use_dhcp()
{
	${IPC_SEND} netcfg-requesting-dhcp-address
	udhcpc -x hostname:"${HOSTNAME}" -b -s ${DHCP_SCRIPT} -i ${IFACE}
}

# configure static network
use_static()
{
	ifconfig ${IFACE} ${IP} netmask ${NETMASK}
	route add -net 224.0.0.0 netmask 240.0.0.0 ${IFACE}
	route del default 2> /dev/null
	if [ ! -z ${GATEWAY} ] && [ ! _${GATEWAY} = _0.0.0.0 ]
	then
		route add default gw ${GATEWAY}
	fi

	# set nameserver 1
	if [ ! -z "${NAMESERVER1}" ]
	then
		printf "nameserver %s\\n" "${NAMESERVER1}" >> ${RESOLV_CONF}
	fi

	# set nameserver 2
	if [ ! -z "${NAMESERVER2}" ]
	then
		printf "nameserver %s\\n" "${NAMESERVER2}" >> ${RESOLV_CONF}
	fi

	${IPC_SEND} netcfg-static-address-configured
}

start() {
	log "Starting network ... "

	# prepare
	touch ${RESOLV_CONF}
	rm -f ${SERVER_ID}
	if [ ! -f ${NETWORK_CFG_FILE} ]
	then
		log "${NETWORK_CFG_FILE} not found copying template."
		cp ${NETWORK_CFG_FILE_TEMPLATE} ${NETWORK_CFG_FILE}
	fi

	# read config file
	. ${NETWORK_CFG_FILE}

	# set new hostname
	MAC=$(cat /opt/extparam/mac_address_0 | sed 's/://g' | tr '[:upper:]' '[:lower:]') 
	DEVICEID=$(cat /opt/extparam/device_id)
	HOSTNAME="${DEVICEID}-${MAC}" 
	log "Setting hostname to ${HOSTNAME}"
	hostname ${HOSTNAME}

	# init IFACE
	ifconfig ${IFACE} up

	# clean up processes
	killall -q udhcpc
	killall -q zcip

	# check dhcp mode
	if [ _${MODE} = _DHCP ]
	then
		use_dhcp
    exit 0
	fi

	use_static

	log "done."
}

stop() {
	log "Stopping network ..."

	${IPC_SEND} netcfg-unconfigured

	# Cleaning up routes
	route del -net 224.0.0.0 netmask 240.0.0.0 2> /dev/null
	route del default 2> /dev/null

	# Killing processes
	killall -q udhcpc

	# Removing unused files
	rm -rf ${RESOLV_CONF}

	# shut down interface
	ifconfig ${IFACE} down

	log "done."
}

restart() {
	stop
	start
	[ -f /etc/init.d/S60openvpn ] && /etc/init.d/S60openvpn network_refresh
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		restart
		;;
	*)
		printf "Usage: %s {start|stop|restart}\\n" "$0"
		exit 1
esac

exit 0
