#!/bin/sh

# Source function library
. /etc/init.d/functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC=udhcpc
DAEMON=udhcpc
IFACE=eth0
PIDFILE_BASE=/var/run/udhcpc
PIDFILE=${PIDFILE_BASE}.${IFACE}.pid

export PATH

if [ -e /etc/default/vlans ];then
	source /etc/default/vlans
fi;

if [ -e /etc/default/ppp ];then
	source /etc/default/ppp
else
	ENABLE=0;
fi;

set -e

configure_vlan() {
	if [ -e /etc/default/vlan_${1} ];then
		source /etc/default/vlan_${1}
	else
		return 0;
	fi;

	if [ ! -d /sys/class/net/${IFACE}.${1} ];then
		/sbin/ip link add link ${IFACE} name ${IFACE}.${1} type vlan id ${1}
		/sbin/ip link set ${IFACE}.${1} up
	fi;

	if [ "${2}" ];then
		DHCP=${2}
	fi;
	if [ "${DHCP}" == "1" ];then
		start-stop-daemon --start -p ${PIDFILE_BASE}.${IFACE}_${1}.pid $DAEMON -- -R -b -p ${PIDFILE_BASE}.${IFACE}_${1}.pid -i ${IFACE}.${1}
	else
		interface=${IFACE}.${1} /etc/udhcpc.d/90comb-static renew | :
	fi;
}

case $1 in
	start)
		echo -n "Starting $DESC: "
		if [ "${ENABLE-0}" == "1" ] && [ ! "${VLAN}" ];then
			if [ "${DHCP-1}" == "1" ];then
				start-stop-daemon --start -p $PIDFILE $DAEMON -- -R -b -p /var/run/udhcpc.${IFACE}.pid -i ${IFACE}
			else
				interface=${IFACE} /etc/udhcpc.d/90comb-static renew | :
				interface=${IFACE} /etc/udhcpc.d/99kernel-pnp renew | :
			fi;
		else
			start-stop-daemon --start -p $PIDFILE $DAEMON -- -R -b -p /var/run/udhcpc.${IFACE}.pid -i ${IFACE}
		fi;
		if [ "${VLANS}" ];then
			for vlanid in ${VLANS};do
				if [ "${ENABLE}" == "1" ] && [ "${vlanid}" == "${VLAN}" ];then
					continue;
				fi;
				(configure_vlan ${vlanid})
			done;
			if [ "${ENABLE}" == "1" ] && [ "${VLAN}" ];then
				(configure_vlan ${VLAN} ${DHCP})
			fi;
		fi;
	;;
	stop)
		echo -n "Stopping $DESC: "
		if [ -e $PIDFILE ];then
			start-stop-daemon --stop -s SIGKILL -p $PIDFILE $DAEMON
			rm $PIDFILE
			ifconfig ${IFACE}:dhcp down | :
		fi;
		if [ "${VLANS}" ];then
			for vlanid in ${VLANS};do
				if [ "${ENABLE}" == "1" ] && [ "${vlanid}" == "${VLAN}" ];then
					continue;
				fi;
				if [ -e ${PIDFILE_BASE}.${IFACE}_${vlanid}.pid ];then
					start-stop-daemon --stop -s SIGKILL -p ${PIDFILE_BASE}.${IFACE}_${vlanid}.pid
					rm ${PIDFILE_BASE}.${IFACE}_${vlanid}.pid
					ifconfig ${IFACE}.${vlanid}:dhcp down | :
				fi;
			done;
			if [ "${ENABLE}" == "1" ] && [ "${VLAN}" ] && [ -e ${PIDFILE_BASE}.${IFACE}_${VLAN}.pid ];then
				start-stop-daemon --stop -s SIGKILL -p ${PIDFILE_BASE}.${IFACE}_${VLAN}.pid
				rm ${PIDFILE_BASE}.${IFACE}_${VLAN}.pid
				ifconfig ${IFACE}.${VLAN}:dhcp down | :
			fi;
		fi;
	;;
	restart|force-reload)
		$0 stop
		sleep 1
		$0 start
	;;
	status)
		status ${DAEMON} || exit $?
	;;
	*)
		N=/etc/init.d/udhcpc
		echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
		exit 1
	;;
esac

exit 0
