#!/bin/sh -e

RCLIB=/lib/rcscripts
. $RCLIB/sh/error.sh

notify_netd () {
	gdbus call --address unix:path=/run/netd/internal -d a.b -o / \
		-m com.axis.Net.Internal.DHCPV4 $interface \
		"{'address': <'$ip'>,
'netmask': <'$subnet'>,
'broadcast': <'$broadcast'>,
'routers': <'$router'>,
'hostname': <'$hostname'>,
'domainname': <'$domain'>,
'searchdomains': <'$search'>,
'nameservers': <'$dns'>,
'timeservers': <'$ntpsrv'>}" >/dev/null ||
		error "$0: Failed to notify netd of updated DHCPv4 lease for $interface"
}

case $1 in
	deconfig)
		active_state=$(systemctl is-active dhcp4@${interface}.service || :)
		# Do not notify netd if service is deactivating. Either netd stopped dhcp
		# client or system is shutting down, either way, let netd handle the
		# clearing of the lease
		[ "$active_state" = deactivating ] || notify_netd
		;
	leasefail)
		warning "Could not obtain a DHCPv4 lease"
		notify_netd
		;
	nak)
		warning "Got NAK from the DHCPv4 server"
		notify_netd
		;
	bound|renew)
		# Validate address and netmask
		[ "$ip" ] && [ "$subnet" ] ||
			error "DHCPv4 address: $ip and/or mask: $subnet' missing"
		# If no broadcast is set, calculate one from mask
		if [ -z "$broadcast" ]; then
			# The output of this command looks like this: BROADCAST=192.168.0.255
			eval $(ipcalc -b $ip $subnet) ||
				error "Failed to calculate broadcast from DHCPv4 IP:$ip mask:$subnet"
			broadcast=$BROADCAST
		fi
		# Notify netd that the lease has been updated
		notify_netd
		;
	*)
		error "Unknown DHCPv4 state set when calling script ($1)"
		;
esac