#!/usr/sbin/openrc-run

description="IPv4 DHCP client with IPv4LL support"

command="/usr/sbin/dhcpcd"
pidfile="/var/run/dhcpcd.pid"

depend() {
	provide net
	need localmount
	use logger
	after bootmisc
	before dns
}

sanity() {
	local x

	case "$("$command" --version)" in
	[1234].*)
		eerror "Not running dhcpcd because an older version is currently preferred"
		return 6
		;;
	esac

	for x in /var/run/dhcpcd-*.pid; do
		[ -f "$x" ] || continue
		eerror "Not running dhcpcd because there is already an interface specific instance"
		eerror "$x"
		return 6
	done

	if grep -q "^[[:space:]]*iface[[:space:]]*.*[[:space:]]*inet[[:space:]]*dhcp" \
		/etc/network/interfaces; then
		eerror "Not running dhcpcd because /etc/network/interfaces defines DHCP interfaces"
		return 6
	fi
	return 0
}

start_pre() {
	[ -x "$command" ] || return 1
}

start() {
	sanity || return $?
	if [ -f "$pidfile" ] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then
		ewarn "dhcpcd is already running"
		return 0
	fi
	ebegin "Starting ${RC_SVCNAME}"
	"$command"
	eend $?
}

stop() {
	sanity || return $?
	ebegin "Stopping ${RC_SVCNAME}"
	"$command" -x
	eend $?
}

restart() {
	stop || true
	start
}

reload() {
	if [ ! -f "$pidfile" ] || ! kill -0 "$(cat "$pidfile")" 2>/dev/null; then
		eerror "dhcpcd is not running"
		return 7
	fi
	sanity || return $?
	ebegin "Reloading ${RC_SVCNAME}"
	"$command" -n
	eend $?
}
