#!/bin/sh -e
#
# 0044interval_overlap_0 - Add overlapping and non-overlapping intervals
#
# Check that adding overlapping intervals to a set returns an error, unless:
# - the inserted element overlaps entirely, that is, it's identical to an
#   existing one
# - for concatenated ranges, the new element is less specific than any existing
#   overlapping element, as elements are evaluated in order of insertion

#	Accept	Interval	List
intervals_simple="
	y	 0 -  2		0-2
	y	 0 -  2		0-2
	n	 0 -  1		0-2
	n	 0 -  3		0-2
	y	 3 - 10		0-2, 3-10
	n	 3 -  9		0-2, 3-10
	n	 4 - 10		0-2, 3-10
	n	 4 -  9		0-2, 3-10
	y	20 - 30		0-2, 3-10, 20-30
	y	11 - 12		0-2, 3-10, 11-12, 20-30
	y	13 - 19		0-2, 3-10, 11-12, 13-19, 20-30
	n	25 - 40		0-2, 3-10, 11-12, 13-19, 20-30
	y	50 - 60		0-2, 3-10, 11-12, 13-19, 20-30, 50-60
	y	31 - 49		0-2, 3-10, 11-12, 13-19, 20-30, 31-49, 50-60
	n	59 - 60		0-2, 3-10, 11-12, 13-19, 20-30, 31-49, 50-60
"

intervals_concat="
	y	0-2 . 0-3	0-2 . 0-3
	y	0-2 . 0-3	0-2 . 0-3
	n	0-1 . 0-2	0-2 . 0-3
	y	10-20 . 30-40	0-2 . 0-3, 10-20 . 30-40
	n	15-20 . 50-60	0-2 . 0-3, 10-20 . 30-40, 15-20 . 50-60
	y	3-9 . 4-29	0-2 . 0-3, 10-20 . 30-40, 15-20 . 50-60, 3-9 . 4-29
	y	3-9 . 4-29	0-2 . 0-3, 10-20 . 30-40, 15-20 . 50-60, 3-9 . 4-29
	n	11-19 . 30-40	0-2 . 0-3, 10-20 . 30-40, 15-20 . 50-60, 3-9 . 4-29
	y	15-20 . 49-61	0-2 . 0-3, 10-20 . 30-40, 15-20 . 50-60, 3-9 . 4-29, 15-20 . 49-61
"

$NFT add table t
$NFT add set t s '{ type inet_service ; flags interval ; }'
$NFT add set t c '{ type inet_service . inet_service ; flags interval ; }'

IFS='	
'
set="s"
for t in ${intervals_simple} switch ${intervals_concat}; do
	[ "${t}" = "switch" ] && set="c"         && continue
	[ -z "${pass}" ]      && pass="${t}"     && continue
	[ -z "${interval}" ]  && interval="${t}" && continue

	if [ "${pass}" = "y" ]; then
		$NFT add element t ${set} "{ ${interval} }"
	else
		! $NFT add element t ${set} "{ ${interval} }" 2>/dev/null
	fi
	$NFT list set t ${set} | tr -d '\n\t' | tr -s ' ' | \
		grep -q "elements = { ${t} }"

	pass=
	interval=
done

unset IFS
