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

#include "testnet.h"
#include <librecast.h>
#include <limits.h>
#include <mld_pvt.h>
#include <net/if.h>
#include <sys/types.h>
#include <ifaddrs.h>

int main(void)
{
	mld_t *mld;
	char ifname[IF_NAMESIZE];
	unsigned int ifx;
	int interfaces = 0;
	int rc;

	test_name("mld_add_iface() / mld_del_iface()");
	test_require_net(TEST_NET_BASIC);

	ifx = get_multicast_if();
	test_assert(ifx, "get_multicast_if() - find multicast capable interface");
	if (!ifx) return TEST_WARN;
	mld = mld_init(0);
	test_assert(mld != NULL, "mld_init() returned %p", (void *)mld);
	if (!mld) return test_status;
	if_indextoname(ifx, ifname);
	rc = mld_add_iface(mld, ifx, ifname);
	test_assert(rc == 0, "interface added, return 0: %s", strerror(errno));
	rc = mld_add_iface(mld, ifx, ifname);
	test_assert(rc == -1, "interface exists, return -1");
	for (mld_iface_t *i = mld->iface; i; i = i->next) {
		if (!strcmp(i->ifname, ifname)) interfaces++;
	}
	test_assert(interfaces == 1, "mld_add_iface(): ensure duplicate interfaces not added");

	rc = mld_del_iface(mld, ifx);
	test_assert(rc == 0, "interface deleted, return 0: %s", strerror(errno));
	interfaces = 0;
	for (mld_iface_t *i = mld->iface; i; i = i->next) {
		if (!strcmp(i->ifname, ifname)) interfaces++;
	}
	test_assert(interfaces == 0, "mld_del_iface(): ensure interfaces deleted");

	rc = mld_del_iface(mld, ifx);
	test_assert(rc == -1, "try to delete interface that is already deleted, return -1");

	mld_free(mld);
	return test_status;
}
