#!/bin/sh

# Copyright (C) 2007, Digium, Inc.
#
# Brandon Kruse <bkruse@digium.com>
#
# Script to apply network settings from the GUI.

WAN_INTERFACE="eth0"  # default value, will be replaced by the value from network.params
DHCPD_CONFIG="/etc/udhcpd.conf"
DHCPD_BIN="`which udhcpd`"
DHCPD_PROCNAME="udhcpd"
NTP_CONFIG="/etc/config/ntp.conf"

ARG_FILE="/etc/asterisk/scripts/network.params"

# We are going to set default values
if [ -f ${ARG_FILE} ]; then
	echo "Configuring with network.params"
	. ${ARG_FILE} 	# Include the file that has the variables in it, written from the GUI.
else
	echo "Configuring interface for the first time, or after configuration loss."
	DHCP_WAN_PROVISION=off
	TFTP_LAN=http://0.0.0.0:8088/phoneprov
fi

# Now for the real logic in the script.
# Note: You CANNOT use functions with msh/busybox.

# Set our time server
killall -9 ntpd 2>/dev/null
echo "### Autogenerated conf file" > ${NTP_CONFIG}
echo "" >> ${NTP_CONFIG}
if [ "${NTP_ADDRESS}" != "" ]; then
	ntpdate ${NTP_ADDRESS} 
	echo "server   ${NTP_ADDRESS}" >> ${NTP_CONFIG}
fi
echo "server 127.127.1.1 prefer iburst" >> ${NTP_CONFIG}
echo "fudge 127.127.1.1 stratum 5" >> ${NTP_CONFIG}
echo "" >> ${NTP_CONFIG}
echo "disable auth" >> ${NTP_CONFIG}
#daemon is started as last thing in script

if [ "${DHCP_WAN_PROVISION}" = "on" ]; then
	echo "Setting limited udhcpd on WAN for provisioning"
# Now we will edit /etc/udhcpd.conf
	echo "interface ${WAN_INTERFACE}" > ${DHCPD_CONFIG}
# Set leases to 0 so that IP Offers will not be sent out
	echo "max_leases 0" >> ${DHCPD_CONFIG}
	if [ "${TFTP_LAN}" != "" ]; then
		echo "opt tftp ${TFTP_LAN}" >> ${DHCPD_CONFIG}
	fi
	echo "opt ntpsrv 0.0.0.0" >> ${DHCPD_CONFIG}
# Stop and restart our dhcp server.
	killall -9 ${DHCPD_PROCNAME} 2> /dev/null
	${DHCPD_BIN} > /dev/null 2> /dev/null &
else 
	echo "There is NO udhcpd"
	killall -9 ${DHCPD_PROCNAME} 2> /dev/null
fi

#Finish ntp daemon work. 
ntpd -g &
