#!/bin/bash

# Bring up/down dhcp client

. /proc/fiad/hw-info
. /etc/sysconfig/rc.conf
. /etc/sysconfig/network.conf
. /bin/network-functions
. /var/run/interfaces
. /etc/image_features

PIDFILE=/var/run/dhclient.pid
SERVICE=dhclient
PROCESS_NAME=dhclient

INITDPID=/var/run/initd."$SERVICE".pid
DHCLIENT_LEASED=/var/state/dhcp/dhclient.leases

do_start ()
{
	if ! ServiceCheckRunning1 ; then
		return $?
	fi

	/etc/init.d/softdogd wait
	echo "$$" > $INITDPID

#if [ "$FEATURE_FIREWALL" = "1" ] ; then
#	/bin/firewall_blocking system add dhcpclient > /dev/null 2>&1
#fi

	WAN_MAC=$(/bin/ip link show dev $PHYS_WAN | /bin/grep ether | /bin/cut -d ' ' -f 6)

	# create correct dhclient configuration
	echo "# dhclient.conf. Automatically created: `date`" > /var/run/dhclient.conf
	echo "send host-name \"$HOSTNAME\";" >> /var/run/dhclient.conf
	echo "send dhcp-client-identifier \"$WAN_MAC\";" >> /var/run/dhclient.conf
	echo "send vendor-class-identifier \"$WAN_MAC $BOARD_TYPE $(/bin/cat /etc/image_label.txt)\";" >> /var/run/dhclient.conf
	echo "request subnet-mask, broadcast-address, time-offset, routers, domain-name, domain-name-servers, host-name, tftp-server-name;" >> /var/run/dhclient.conf
	echo "option classless-static-routes code 121 = array of { integer 8, ip-address, ip-address };" >> /var/run/dhclient.conf
	echo "timeout 10;" >> /var/run/dhclient.conf
	echo "retry 60;" >> /var/run/dhclient.conf

	PHYS_INTERFACE=$PHYS_WAN
	if [ "$FEATURE_VLAN" = "1" ] ; then 
		if [ "$START_VLANGW" = "true" ] ; then
			PHYS_INTERFACE=$VLAN_INTERFACE
		fi
	fi

	/bin/setsid /bin/$PROCESS_NAME -4 $PHYS_INTERFACE -lf $DHCLIENT_LEASED > /dev/null 2>&1

	rm -f $INITDPID

	ServiceCheckRunning2

	return $?
}

do_stop ()
{
	if ! ServiceStop ; then
		return $?
	fi
	/etc/init.d/softdogd wait

	# killing dhclient is not enough.. we need to stop all dependant services
	. /var/run/interfaces
	export interface=$PHYS_WAN
	export reason=STOP
	/etc/dhclient-script

#if [ "$FEATURE_FIREWALL" = "1" ] ; then
#	/bin/firewall system del dhcpclient > /dev/null 2>&1
#fi

	# disable interface
	/bin/ip -4 address flush dev $PHYS_WAN > /dev/null 2>&1
	/bin/ip -4 link set down dev $PHYS_WAN > /dev/null 2>&1

	return $?
}

do_status ()
{
	ServiceStatus

	return $?
}

if [ -f $INITDPID ] ; then
	if [ "$1" = "stop" ] || [ "$1" = "restart" ] ; then
		echo "$0: killing all dhclient programs"
		for testpid in $(/bin/pidof dhclient) ; do
			if [ "$$" != "$testpid" ] ; then
				echo "$0: kill sent to pid $testpid"
				/bin/kill $testpid
			fi
		done
		rm -f $INITDPID
	else
		echo "$0: init.d script already running"
		exit 10
	fi
fi

case "$1" in
	start)
		do_start
		;;
	stop)
		do_stop
		;;
	status)
		do_status
		;;
	restart)
		do_stop
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
esac

exit $?
