#include "qsee_printk.h"

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define LOG_BUF_MAX 512

static int klog_level = KLOG_INFO_LEVEL;

void klog_set_level(int level) { klog_level = level; }

static int __open_klog(void)
{
	static const char kmsg_device[] = "/dev/kmsg";
	return open(kmsg_device, O_WRONLY | O_CLOEXEC);
}

void klog_writev(int level, const char *buf, int buf_len)
{
	if (level > klog_level)
		return;

	int klog_fd = __open_klog();
	if (klog_fd == -1) {
		return;
	}
	write(klog_fd, buf, buf_len);

	close(klog_fd);
}

void klog_write(int level, const char *fmt, ...)
{
	if (level > klog_level)
		return;

	char buf[LOG_BUF_MAX];
	va_list ap;
	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);
	buf[LOG_BUF_MAX - 1] = 0;

	klog_writev(level, buf, strlen(buf));
}
