#!/bin/sh
#
# This file is part of the FreeWRT project. FreeWRT is copyrighted
# material, please see the LICENCE file in the top-level directory
# or at http://www.freewrt.org/licence for details.
#
# Christian Fischer <spaetzle@freewrt.org>
#


method_preup() {
	dhcp_up || exit 1

	# don't handle any failures, it's really not my problem if that goes wrong
	main_exec_inlinehooks

	main_up || exit 1
	RT_BB_NOEXEC=1
}

method_down() {
	dhcp_down

	# don't handle any failures, it's really not my problem if that goes wrong
	main_exec_inlinehooks

	main_postdown || exit 1
	RT_BB_NOEXEC=1
}

dhcp_up() {
	local err

	if ! err=$(ip link set $IFACE up 2>&1 1>&-)
	then
		mprint -s "dhcp_up: $err"
		return 1
	fi

	mkdir -p /var/run/dhcpc

	if [ "${IF_DHCPCLIENT:-""}" != "" -a  "${IF_DHCPCLIENT_OPTS:-""}" != "udhcpc" ]
	then
		if [ -x "$(which $IF_DHCPCLIENT)" ]
		then
			err=$(eval $IF_DHCPCLIENT ${IF_DHCPCLIENT_OPTS:-""} 2>&1 1>&-) || mprint -s "dhcp_up: $err" &
			if [ -n ${!:-""} ]
			then
				echo $! > /var/run/dhcpc/${IF_DHCPCLIENT}.${IFACE}.pid
				return 0
			else
				mprint -s "dhcp_up: dhcp client start failed"
				return 1
			fi
		fi
		mprint -s "$IF_DHCPCCLIENT not found, using built-in udhcpcd"
	fi

	if ! err=$(udhcpc -b -t 1 -p /var/run/dhcpc/udhcpc.${IFACE}.pid -i $IFACE ${IF_HOSTNAME:+"-H $IF_HOSTNAME"} ${IF_CLIENTID:+"-c $IF_CLIENTID"} \
				${IF_SCRIPT:+"-s $IF_SCRIPT"} 2>&1 1>&-)
	then
		mprint -s "dhcp_up: $err"
		return 1
	fi

	return 0
}

dhcp_down() {
	local err pid

	for pidfile in /var/run/dhcpc/*
	do
		if echo $pidfile | grep -q .${IFACE}.
		then
			pid="$(cat $pidfile 2>&-)"
			if [ -n "$pid" ] -a -d "/proc/$pid" ]
			then
				err=$(kill -TERM $pid 2>&1 1>&-) || mprint -s "dhcp_down: $err"
				rm -f $pidfile 2>&-
			fi
		fi
	done

	if is_up
	then
		err=$(ip addr flush dev $IFACE 2>&1 1>&-) || mprint -s "dhcp_down: $err"
		err=$(ip link set $IFACE down 2>&1 1>&-) || mprint -s "dhcp_down: $err"
	fi
}

# vim:ts=4
