#!/usr/local/bin/cbsd
#v10.0.0
# return 0 - not in NC pool range
# return 1 - all ok
# return 2 - ip already in use
# check = 0 - check for pool only 
# check = 1 - check for local interface
# check = 2 - check the availability of IP
MYARG="ip check"
MYOPTARG=""
MYDESC="Check for IP exist or in pool"

. ${subr}
. ${tools}
init $*

CL_IP=${ip%%/*}
INNET=0

check_for_pool()
{
	local _ippool

	for _ippool in ${node_ippool}; do
		NC_RANGE=$( /bin/echo ${_ippool} |/usr/bin/tr "/" " " )
		netmask ${NC_RANGE} ${CL_IP} > /dev/null 2>&1
		res=$?

		if [ ${res} -eq 1 ]; then
			INNET=$((INNET + 1))
		fi
	done
}

check_local_ip()
{
	${miscdir}/chk_arp_byip --ip=${CL_IP} > /dev/null 2>&1
	return $?
}

## MAIN

# this part is for not empty IPs or DHCP mode
case ${CL_IP} in
	[Dd][Hh][Cc][Pp]|0)
		exit 1
		;;
esac

# force IPv6 to check mode 2 (via ping)
# due to 0,1 not implemented yet
iptype ${CL_IP}
[ $? -eq 2 ] && check=2

case ${check} in
	0)
		check_for_pool
		[ ${INNET} -gt 0 ] && exit 1
		exit 0
		;;
	1)
		check_local_ip
		[ $? -eq 0 ] && exit 1
		exit 2
		;;
	2)
		iptype ${CL_IP}
		case $? in
			1)
				/sbin/ping -n -t1 -i0.3 -W 300 -c2 -q ${CL_IP} > /dev/null 2>&1
				[ $? -eq 0 ] && exit 2
				exit 1
				;;
			2)
				/sbin/ping6 -n -X3 -i0.5 -c3 -q ${CL_IP} > /dev/null 2>&1
				[ $? -eq 0 ] && exit 2
				exit 1
				;;
		esac
		;;
esac

exit 0
