#!/bin/sh -e

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

notify_netd () {
	gdbus call -y -d com.axis.Net.Private -o / \
		-m com.axis.Net.Internal.DHCPV4 $interface \
		"{'address': <'$ip'>,
'netmask': <'$subnet'>,
'broadcast': <'$broadcast'>,
'routers': <'$router'>,
'hostname': <'$hostname'>,
'domainname': <'$domain'>,
'searchdomains': <'$search'>,
'nameservers': <'$dns'>,
'tftp': <'$tftp'>,
'timeservers': <'$ntpsrv'>}" >/dev/null || [ $? -eq $SIGTERM_EXIT_CODE ] ||
		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"
		# Clear address to tell netd to deconfigure any leased addresses
		ip=""
		notify_netd
		;
	nak)
		warning "Got NAK from the DHCPv4 server"
		# Clear address to tell netd to deconfigure any leased addresses
		ip=""
		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
		# Print server IP when bound
		[ "$1" != "bound" ] || information "udhcpc: lease obtained from $siaddr"
		# Notify netd that the lease has been updated
		notify_netd
		;
	*)
		error "Unknown DHCPv4 state set when calling script ($1)"
		;
esac