#!/bin/bash

# Test case: Verify 'last' expression tagging behavior
# - 'last' should be tagged as "never-matched" initially
# - After matching a packet, it should be tagged with "last matched at <timestamp>"

ip link set lo up

set -e

die() {
	echo "FAIL: $@"
	$NFT list ruleset
}

# Create a simple ruleset with one base chain and a rule using 'last'
$NFT add table inet filter
$NFT add chain inet filter input '{ type filter hook input priority 0; }'
$NFT add rule inet filter input icmp type echo-request last

# Get the chain with the 'last' rule
rule_dump=$($NFT list chain inet filter input)
echo "$rule_dump"

# Check initial state of 'last' — should be "never-matched"
if echo "$rule_dump" | grep -q 'last used never'; then
	echo "PASS: Initial 'last' state is never"
else
	die "'last' should be 'never'"
fi

# Send one ICMP echo-request packet
# Use 'ping' with count=1 to generate one ICMP echo request (requires privileges)
# Fall back to raw packet if ping fails (e.g., no network stack or permissions)
ping -c 1 -W 1 127.0.0.1

sleep 1

# Check 'last' after packet arrival
rule_dump=$($NFT list chain inet filter input)
if ! echo "$rule_dump" | grep -q 'last used [1-3]s'; then
	die "'last' should be matched after packet"
fi

# Wait a few seconds and check again — timestamp should remain unchanged (not auto-updating)
sleep 3

rule_dump=$($NFT list chain inet filter input)
if ! echo "$rule_dump" | grep -q 'last used [4-6]s'; then
	die "'last' timestamp unexpectedly changed"
fi
