#!/bin/bash

# NFT_TEST_REQUIRES(NFT_TEST_HAVE_bitwise_multireg)
# NFT_TEST_REQUIRES(NFT_TEST_HAVE_bitshift)

set -e
ret=0

ip link set lo up

$NFT -f - <<EOF
table ip test-binop {
	chain in {
		type filter hook input priority 0

		icmp type echo-request jump {
			meta mark 0 counter
			meta mark 1 counter
			meta mark 2 counter
			meta mark 3 counter
		}
	}

	chain out {
		type filter hook output priority 0

		icmp type echo-request meta mark set ip saddr ^ ip daddr map { 0.0.0.0 : 1, 0.1.2.2 : 2, 127.0.0.1 : 3 }
	}
}
EOF

test_match()
{
	mark="$1"
	packets="$2"
	str=$(printf "mark 0x%08x" $mark)

	if ! $NFT list chain test-binop in | grep "$str" | grep "packets $packets"; then
		$NFT list chain test-binop in
		echo "Failed counter for mark $mark: not $packets"
		ret=1
	fi
}

test_ping_and_match()
{
	ping="$1"
	mark="$2"
	packets="$3"

	ping -q -c 1 "$ping"
	test_match "$mark" "$packets"
}

test_ping_and_match "127.0.0.1" 1 1
test_ping_and_match "127.1.2.3" 2 1

# validation of 0 counters done via dump.
# validation of 1-counters done manually to make
# sure each ping triggers the expected counter.

exit $ret
