#!/sbin/openrc-run

description="IPv4 DHCP client with IPv4LL support"

command="/usr/sbin/dhcpcd"
pidfile="/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 /run/dhcpcd-*.pid /run/dhcpcd/*.pid /run/dhcpcd/pid; do
		[ -e "$x" ] || continue
		[ -f "$x" ] || continue
		eerror "Not running dhcpcd because there is already an interface specific instance"
		eerror "$x"
		return 6
	done

	if grep -qE "^[[:space:]]*iface[[:space:]]*.*[[:space:]]*inet[[:space:]]*dhcp|[[:space:]]*post-up[[:space:]].*dhcpcd" \
		/etc/network/interfaces 2>/dev/null; then
		eerror "Not running dhcpcd because /etc/network/interfaces already drives dhcpcd"
		return 6
	fi
	return 0
}

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

start() {
	# simple-netaid owns DHCP; supervised/system-wide dhcpcd races with
	# per-iface dhcpcd -4. Successful no-op (like DM when not default).
	if [ -x /usr/sbin/snetaid ]; then
		einfo "Not starting dhcpcd; simple-netaid (snetaid) owns networking"
		return 0
	fi
	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() {
	# Do not fail shutdown if dhcpcd was never meant to run (simple-netaid, etc.).
	ebegin "Stopping ${RC_SVCNAME}"
	if [ -x "$command" ]; then
		"$command" -x >/dev/null 2>&1 || true
	fi
	eend 0
}

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 $?
}
