/*
 * Created by jiaqiang.ye@lnxall.com
 *
 * Simple application level helper functions for Lnxall gateways
 *
 * 2023/07/07
 */

#ifndef __LNXALL_UBUS_H
#define __LNXALL_UBUS_H 1
#ifdef __cplusplus
extern "C" {
#endif

/* identity log level mappiing from `syslog.h */
#define	LNXALL_LOGEMERG     0
#define	LNXALL_LOGALERT     1
#define	LNXALL_LOGCRIT      2
#define	LNXALL_LOGERR       3
#define	LNXALL_LOGWARNING   4
#define	LNXALL_LOGNOTICE    5
#define	LNXALL_LOGINFO      6
#define	LNXALL_LOGDEBUG     7

int lnxall_loglevel_get(void);

/*
 * If `dftsig is non-zero, the function will delay
 * one second before restoring default actions for
 * signals: SIGINT/SIGTERM
 */
int lnxall_loglevel_set(int newlevel, int dftsig);


int lnxall_syslog(int level, const char *__format, ...)
	__attribute__((format(printf, 2, 3)));

int lnxall_syslog_uid(int level, int uid, const char *__format, ...)
	__attribute__((format(printf, 3, 4)));


#define dbg_syslog(log_level_, log_fmt_, ...) \
	lnxall_syslog(log_level_, "%s:%d " log_fmt_, __FILE__, __LINE__, ## __VA_ARGS__)

#define dbg_syslog_uid(log_level_, log_uid_, log_fmt_, ...) \
	lnxall_syslog_uid(log_level_, log_uid_, "%s:%d " log_fmt_, __FILE__, __LINE__, ## __VA_ARGS__)


#define dbg_syslog_hex(log_level_, buf_ptr_, buf_len_, log_fmt_, ...) \
	do { \
		int lino_ = __LINE__; \
		const char * file_ = __FILE__; \
		char * buf_hex = lnxall_bin2hex(buf_ptr_, buf_len_);  \
		lnxall_syslog(log_level_, "%s:%d " log_fmt_, file_, lino_, ## __VA_ARGS__); \
		if (buf_hex) { \
			lnxall_syslog(log_level_, "%s:%d ->\n%s", file_, lino_, buf_hex); \
			free(buf_hex); \
		} \
	} while (0)

#define dbg_syslog_hex_uid(log_level_, log_uid_, buf_ptr_, buf_len_, log_fmt_, ...) \
	do { \
		int lino_ = __LINE__; \
		const char * file_ = __FILE__; \
		char * buf_hex = lnxall_bin2hex(buf_ptr_, buf_len_);  \
		lnxall_syslog_uid(log_level_, log_uid_, "%s:%d " log_fmt_, file_, lino_, ## __VA_ARGS__); \
		if (buf_hex) { \
			lnxall_syslog_uid(log_level_, log_uid_, "%s:%d ->\n%s", file_, lino_, buf_hex); \
			free(buf_hex); \
		} \
	} while (0)


char * lnxall_bin2hex(const void * ptr_, size_t plen);

int lnxall_log_reinit(const char * appName, int dftsig);

#ifdef __cplusplus
};
#endif
#endif
