-- SPDX-License-Identifier: GPL-3.0-or-later
local ffi = require('ffi')

{% raw %}
modules.load('stats')

FWD_TARGET = policy.FORWARD('192.0.2.1')

function check_stats(got)
	log_info(ffi.C.LOG_GRP_TESTS, 'checking if stat values match expected values:')
	local expected = {
		['answer'] = {
			['cd'] = 2,
			['cached'] = 1,
			['nodata'] = 1,
			['noerror'] = 2,
			['nxdomain'] = 1,
			['servfail'] = 2,
			['edns0'] = 6,
			['ra'] = 6,
			['rd'] = 5,
			['do'] = 1,
			['ad'] = 0,
			['tc'] = 0,
			['aa'] = 0,
			['total'] = 6
		}
	}
	print(table_print(expected))

	local ok = true
	for sup_key, sup in pairs(expected) do
		for sub_key, expval in pairs(sup) do
			if got[sup_key][sub_key] ~= expval then
				log_info(ffi.C.LOG_GRP_TESTS,
				    'ERROR: stats key ' .. key
				    .. ' has unexpected value'
				    .. ' (expected ' .. tostring(expval)
				    .. ' got ' .. tostring(got[key] .. ')'))
				ok = false
			end
		end
	end
	if ok then
		log_info(ffi.C.LOG_GRP_TESTS, 'no problem found')
		return FWD_TARGET
	else
		return policy.DENY_MSG('Stats test failure')
	end
end

function reply_result(state, req)
	local got = stats.list()
	log_info(ffi.C.LOG_GRP_TESTS, 'current stats.list() values:')
	print(table_print(got))
	local result = check_stats(got)
	return result(state, req)
end
policy.add(policy.all(policy.FLAGS('PASSTHRU_LEGACY'))) -- the test isn't written with this in mind
policy.add(policy.pattern(reply_result, 'stats.test.'))
policy.add(policy.all(FWD_TARGET)) -- avoid iteration

-- make sure DNSSEC is turned off for tests
trust_anchors.remove('.')

-- Enable queries without RD bit
pcall(modules.unload, 'refuse_nord')

-- Disable RFC5011 TA update
if ta_update then
        modules.unload('ta_update')
end

-- Disable RFC8145 signaling, scenario doesn't provide expected answers
if ta_signal_query then
        modules.unload('ta_signal_query')
end

-- Disable RFC8109 priming, scenario doesn't provide expected answers
if priming then
        modules.unload('priming')
end

-- Disable this module because it make one priming query
if detect_time_skew then
        modules.unload('detect_time_skew')
end

_hint_root_file('hints')
cache.size = 2*MB
log_level('debug')
{% endraw %}

net = { '{{SELF_ADDR}}' }


{% if QMIN == "false" %}
option('NO_MINIMIZE', true)
{% else %}
option('NO_MINIMIZE', false)
{% endif %}


-- Self-checks on globals
assert(help() ~= nil)
assert(worker.id ~= nil)
-- Self-checks on facilities
assert(cache.count() == 0)
assert(cache.stats() ~= nil)
assert(cache.backends() ~= nil)
assert(worker.stats() ~= nil)
assert(net.interfaces() ~= nil)
-- Self-checks on loaded stuff
assert(net.list()[1].transport.ip == '{{SELF_ADDR}}')
assert(#modules.list() > 0)
-- Self-check timers
ev = event.recurrent(1 * sec, function (ev) return 1 end)
event.cancel(ev)
ev = event.after(0, function (ev) return 1 end)
