#!/bin/sh

set -e

determine_implementation() {
	[ -x /sbin/dhcpcd ] && echo "dhcpcd" && return
	[ -x /usr/sbin/dhclient ] && echo "dhclient" && return
	[ -x /sbin/udhcpc ] && echo "udhcpc" && return
	echo "could not find a supported DHCP implementation"
	exit 1
}

start() {
	case "$1" in
	dhcpcd)
		[ -z "$IF_HOSTNAME" ] && optargs="$optargs -h $IF_HOSTNAME"
		[ -z "$IF_VENDOR" ] && optargs="$optargs -i $IF_VENDOR"
		[ -z "$IF_CLIENT" ] && optargs="$optargs -i $IF_CLIENT"
		[ -z "$IF_LEASETIME" ] && optargs="$optargs -l $IF_LEASETIME"
		/sbin/dhcpcd $optargs $IFACE
	dhclient)
		/usr/sbin/dhclient -pf /var/run/dhclient.$IFACE.pid $IFACE
		;;
	udhcpc)
		/sbin/udhcpc -b -R -p /var/run/udhcpc.$IFACE.pid -i $IFACE
		;;
	*)
		;;
	esac
}

stop() {
	case "$1" in
	dhcpcd)
		/sbin/dhcpcd -k $IFACE
		;;
	dhclient)
		kill -9 $(cat /var/run/dhclient.$IFACE.pid) 2>/dev/null
		;;
	udhcpc)
		kill $(cat /var/run/udhcpc.$IFACE.pid)
		;;
	*)
		;;
	esac
}

impl=$(determine_implementation)

[ -z "$VERBOSE" ] || set -x

case "$PHASE" in
up) start $impl ;;
down) stop $impl ;;
*) ;;
esac