/*
 * Created by jiaqiang.ye@lnxall.com
 *
 * Simple LNXALL binary logger test
 *
 * 2024/12/24
 */

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>

#include "lnxbinlog.h"

static void test_push_binlog(int fd, size_t loglen, const struct binlog_type * bltype)
{
	size_t i;
	char * p;

	p = (char *) malloc(loglen + 1);
	if (p == NULL)
		return;
	for (i = 0; i < loglen; ++i)
		p[i] = (char) i;

	lnxbinlog_push(bltype, p, loglen);
	free(p);
}

int main(int argc, char *argv[])
{
	int ret, fd;
	size_t ilen;
	uint64_t msize;
	char tbuf[128];
	struct binlog_type bltype;
	struct bldesc_modbus_tcp mtcp_desc;

	fd = -1;
	msize = 0;
	ret = lnxbinlog_setfile("/tmp/what-the-fuck.bin");
	if (ret < 0) {
		fprintf(stderr, "Error, failed to initialize binary-log output file: %d\n", ret);
		fflush(stderr);
		return 1;
	}

	memset(tbuf, 0, sizeof(tbuf));
	ret = lnxbinlog_getfile(tbuf, sizeof(tbuf) - 1, &msize);
	fprintf(stdout, "getfile returned: %d => %s, size: %lld\n",
		ret, tbuf, (unsigned long long) msize);
	fflush(stdout);

	fd = open("/dev/urandom", O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "Error, failed to open random device: %s\n", strerror(errno));
		fflush(stderr);
		return 2;
	}

	mtcp_desc.remote_ip = (unsigned int) inet_addr("172.16.254.254");
	mtcp_desc.port_no = 2024;

	for (ilen = 0; ilen < 32; ++ilen) {
		uint16_t type;
		type = (uint16_t) (ilen + BLTYPE_RS485_R);
		BINLOG_TYPE_INIT(&bltype, type);
		test_push_binlog(fd, ilen, &bltype);
	}

	for (ilen = 0; ilen < 8; ++ilen) {
		uint16_t type;
		type = (uint16_t) (ilen + BLTYPE_CAN_R);
		BINLOG_TYPE_INIT(&bltype, type);
		test_push_binlog(fd, ilen, &bltype);
	}

	for (ilen = 0; ilen < 4; ++ilen) {
		uint16_t type;
		type = (uint16_t) (ilen + BLTYPE_MBTCP_R);
		BINLOG_TYPE_INIT1(&bltype, type, sizeof(mtcp_desc), &mtcp_desc);
		test_push_binlog(fd, ilen, &bltype);
	}

	lnxbinlog_flush(NULL);
	fputs("Done!\n", stdout);
	fflush(stdout);
}
