#!/bin/sh
PATH=$PATH:/usr/local/bin:/sbin:/usr/sbin
. sig_catcher
DEVICE_NAME="eth0"
NOTIFY_SP_DAD_CMD=6
NET_IP4_FAMILY=4
NET_IP6_FAMILY=6

IPv4_DAD()
{
	local ipv4_info=""
	local ipv4_dad_result=0
	local is_device_up=0
	local ret=0
	#IPv4 DAD (Duplicated Address Detection)
	ipv4_info=$(ip -4 addr show dev $DEVICE_NAME)
	is_device_up=$(echo $ipv4_info | grep -c "UP")
	if [ "$is_device_up" -gt 0 ]; then
		#Only check DAD when device is UP.

		ipv4_addr=$(echo $ipv4_info | awk -F 'inet' '{ print $2}' | cut -d ' ' -f 2 | cut -d '/' -f 1)
		dad_info=$(arping -D -c2 -I $DEVICE_NAME $ipv4_addr 2>/dev/null)

		#$?
		#0 : No one uses this IP address.
		#1 : Someone also uses this IP address.
		ipv4_dad_result=$?
		if [ "$ipv4_dad_result" -eq 1 ]; then
			#DAD is asserted.
			ipv4_mac_addr=$(echo $dad_info | cut -d "[" -f 2 | cut -d "]" -f 1 | awk -F ':' '{printf("0x%s 0x%s 0x%s 0x%s 0x%s 0x%s",$1,$2h,$3,$4,$5,$6)}')
			notify_ipv4_addr=$(inet_pton inet $ipv4_addr 2>/dev/null)
			ret=$?
			if [ "$ret" -eq 1 ]; then
				#Success
				notify_ipv4_mac_addr=$(printf "%d " $ipv4_mac_addr)
				notify $NOTIFY_SP_DAD_CMD $NET_IP4_FAMILY $notify_ipv4_mac_addr $notify_ipv4_addr
			else
				sel_logger SP.notice "net_dad 4: Failed to call inet_pton $ret."
			fi
		fi
	fi
}

IPv6_DAD()
{
	local ipv6_info=""
	local ipv6_dad_result=0
	local is_device_up=0
	local notify_ipv6_mac_addr_place_holder="0 0 0 0 0 0"
	#IPv6 DAD (Duplicated Address Detection)
	ipv6_info=$(ip -6 addr show dev $DEVICE_NAME)
	is_device_up=$(echo $ipv6_info | grep -c "UP")
	if [ "$is_device_up" -gt 0 ]; then
		#Only check DAD when device is UP.

		#0 : No one uses this IP address.
		#1 : Someone also uses this IP address.
		ipv6_dad_result=$(ip -6 addr show dev $DEVICE_NAME | grep -c "tentative")

		if [ "$ipv6_dad_result" -eq 1 ]; then
			#DAD is asserted.
			ipv6_addr=$(ip -6 addr show dev $DEVICE_NAME | grep "tentative" | awk -F 'inet6' '{ print $2}' | cut -d '/' -f 1)
			#When kernel detects IPv6 address duplication, this IPv6 address won't be activated.
			#We can't communicate with outside world via IPv6. We can't get the MAC address of the computer which also uses the same IPv6 address.
			notify_ipv6_addr=$(inet_pton inet6 $ipv6_addr 2>/dev/null)
			ret=$?
			if [ "$ret" -eq 1 ]; then
				#Success
				#SP can't get MAC address of the remote node which uses the same IPv6 address. Set MAC address to 0:0:0:0:0:0
				notify $NOTIFY_SP_DAD_CMD $NET_IP6_FAMILY $notify_ipv6_mac_addr_place_holder $notify_ipv6_addr
			else
				sel_logger SP.notice"net_dad 6: Failed to call inet_pton $ret."
			fi
		fi
	fi
}



# Main() start
brdrev=$(cat /var/run/boardrev)
razorl_rev_p2i=3
if [ -f /var/run/RazorS ] || [ -f /var/run/RazorM ] || [ -f /var/run/RazorL -a "$brdrev" -ge "$razorl_rev_p2i" ] ; then
        DEVICE_NAME="eth0.32"
fi

IPv4_DAD

IPv6_DAD




