/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2024 Brett Sheffield <bacs@librecast.net> */

#include "test.h"
#include <librecast_pvt.h>
#include <librecast/router.h>

#define ROUTERS 7

int main(void)
{
	lc_ctx_t *lctx;
	lc_router_t *r[ROUTERS];
	int rc;

	test_name("lc_router_net() - LC_TOPO_MESH");

	lctx = lc_ctx_new();
	if (!test_assert(lctx != NULL, "lc_ctx_new()")) return test_status;

	/* create a full mesh of connected routers */
	rc = lc_router_net(lctx, r, ROUTERS, LC_TOPO_MESH, 0, LC_ROUTER_FLAG_FIXED);
	if (rc) perror("lc_router_net");
	if (!test_assert(rc == 0, "lc_router_net()")) goto err_ctx_free;
	for (int i = 0; i < ROUTERS; i++) {
		test_log("====== ROUTER %i\n", i);

		/* check router parameters */
		if (!test_assert(r[i] != NULL, "r[%i] allocated", i))
			goto err_ctx_free;
		if (!test_assert(r[i]->ctx == lctx, "context set"))
			goto err_ctx_free;
		if (!test_assert(r[i]->flags == LC_ROUTER_FLAG_FIXED, "flags set"))
			goto err_ctx_free;
		if (!test_assert(r[i]->ports == ROUTERS - 1, "ports == %i", r[i]->ports))
			goto err_ctx_free;
	}
	/* now check ports are connected correctly */
	for (int i = 0; i < ROUTERS; i++) {
		int port = i;
		for (int j = 0; j < ROUTERS; j++) {
			if (i >= j) continue;
			if (!test_assert(r[i]->port[port] != NULL, "R[%i]P[%i] connected", i, port))
				goto err_ctx_free;
			test_assert(r[i]->port[port]->pair == r[j]->port[i],
					"R[%i]P[%i] <--> R[%i]P[%i]", i, port, j, i);
			port++;
		}
	}
	test_assert(!lc_router_net_hasloop(r, ROUTERS), "no routing loop with ports DOWN");
	for (int i = 0; i < ROUTERS; i++) lc_router_port_up(r[i], -1);
	test_assert(lc_router_net_hasloop(r, ROUTERS), "routing loop exists with ports UP");
err_ctx_free:
	lc_ctx_free(lctx);
	return test_status;
}
