/*
 * util.h - header file for utility functions.
 *
 * Copyright (C) 2023 IOPSYS Software Solutions AB. All rights reserved.
 *
 * See LICENSE file for license related information.
 *
 */

#ifndef UTIL_H
#define UTIL_H


#include <libubox/list.h>
#include <arpa/inet.h>
#include <sys/time.h>

#include <easy/easy.h>

void do_daemonize(const char *pidfile);
int timeradd_msecs(struct timeval *a, unsigned long msecs, struct timeval *res);

typedef unsigned int ifstatus_t;
typedef unsigned char ifopstatus_t;

enum if_mediatype {
	IF_MEDIA_ETH,
	IF_MEDIA_WIFI,
	IF_MEDIA_PLD,
	IF_MEDIA_MOCA,
	IF_MEDIA_UNKNOWN,
};

int ipaddr_equal(struct ip_address *a, struct ip_address *b);
bool ipaddr_is_zero(struct ip_address *a);

int if_brportnum(const char *ifname);
int if_getmediatype(const char *ifname, enum if_mediatype *mtype);

enum if_mediatype ieee80211_str_to_mediatype(char *m);

int if_getcarrier(const char *ifname, int *carrier);

#ifndef BIT
#define BIT(x)	(1 << (x))
#endif

#define MACFMT		"%02x:%02x:%02x:%02x:%02x:%02x"
#define MAC2STR(_m)	(_m)[0], (_m)[1], (_m)[2], (_m)[3], (_m)[4], (_m)[5]



#ifndef list_flush
#define list_flush(head, type, member)					\
do {									\
	type *__p = NULL, *__tmp;						\
									\
	if (!list_empty(head))						\
		list_for_each_entry_safe(__p, __tmp, head, member) {	\
			list_del(&__p->member);				\
			free(__p);					\
		}							\
} while (0)
#endif


#define foreach_token(t, tokens, delim)	\
	for (t = (tokens ? strtok(tokens, delim) : NULL); \
		 t != NULL; \
		 t = strtok(NULL, delim))

#define blobmsg_add_macaddr(b, f, v)    \
do {                                    \
        char _vstr[18] = {0};           \
        hwaddr_ntoa(v, _vstr);          \
        blobmsg_add_string(b, f, _vstr);\
} while (0)

#endif /* UTIL_H */
