BOGEN_ROOT=/opt/bogen
ULBIN=/usr/local/bin

nyquist_server_setup() {
	case $reason in
		BOUND|RENEW|REBIND|REBOOT)
			[ $reason = BOUND -a "${new_vlan_qos}" != "" ] && old_vlan_qos=
			new_vlan_id_str=$new_vlan_id
			[ -n "$new_vlan_id" ] && new_vlan_id_str=$($ULBIN/dhcp_option2string "vlan-id" "\"$new_vlan_id\"")
			[ -z "$new_vlan_id_str" ] || [ "$new_vlan_id_str" -ge 1 -a "$new_vlan_id_str" -le 4094 ] 2> /dev/null
			if [ $? -ne 0 ]
			then
				logger -p user.warning -t "$0[$$]" "Received invalid VLAN option value($new_vlan_id) - ignored"
			else
				if [ "${interface}" != "eth0${new_vlan_id_str:+.${new_vlan_id_str}}" -o "${new_vlan_qos}" != "${old_vlan_qos}" ]; then
					new_vlan_qos_str=$new_vlan_qos
					[ -n "$new_vlan_qos" ] && new_vlan_qos_str=$($ULBIN/dhcp_option2string "vlan-qos" "\"$new_vlan_qos\"")
					[ -z "$new_vlan_qos_str" ] || [ "$new_vlan_qos_str" -ge 0 -a "$new_vlan_qos_str" -le 7 ] 2> /dev/null
					if [ $? -ne 0 ]
					then
						logger -p user.warning -t "$0[$$]" "Received invalid VLAN QoS option value($new_vlan_qos) - ignored"
						new_vlan_qos_str=
					fi
					systemd-run --no-block --service-type=idle $ULBIN/network_set dhclient dhcp "$new_vlan_id_str" "$new_vlan_qos_str"
				fi
			fi
			# Avoid overwhelming the tftp server by fetching again and again
			[ $reason != RENEW ] && systemd-run --no-block --service-type=idle $ULBIN/update_configuration dhclient
			;;
		EXPIRE|FAIL|RELEASE|STOP)
			$ULBIN/led_controller status red on yes
			;;
		TIMEOUT)
			# Handle dhclient-script bug causing [NYQ-3508] issue
			device_ip=$(ip addr show ${interface} | sed -n -e '/127\.0\.0\.1/d;s/\s*inet\s\+\(\([[:digit:]]\+\.\)\+[[:digit:]]\+\).*/\1/p')
			invalid=1
			if [ -n "${device_ip}" ]; then
				# Test validity of the lease
				epoch_time_now=$(date +%s)
				lease=$((${new_expiry:-0} - ${epoch_time_now:-0}))
				# lease <= new_dhcp_lease_time is valid else we have time skew and RTC has been reset
				[ $lease -le $new_dhcp_lease_time ] && invalid=0 ||ip -4 addr flush dev ${interface}
			fi
			if [ $invalid -eq 1 ]; then
				logger -t $0 -p daemon.warn "DHCP TIMEOUT recorded lease invalid exiting with status 2"
				exit 2
			fi
			;;
	esac
}

nyquist_server_setup
