/*
 * main.c - controller main
 *
 * Copyright (C) 2019-2024 IOPSYS Software Solutions AB. All rights reserved.
 * Copyright (C) 2025 Genexis Sweden AB.
 *
 * Author: anjan.chanda@iopsys.eu
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdint.h>

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include "version.h"
#include "utils/debug.h"
#include "utils/utils.h"

extern void run_controller(void *opts);

const char *PROG_NAME = "mapcontroller";
bool syslogging;
bool usefifo;
bool waitext;
const char *ubus_socket;
const char *outfile_path;
const char *pidfile;
bool daemonize = true;

void usage(char *prog)
{
	fprintf(stderr, "Usage: %s [options]\n", prog);
	fprintf(stderr, "\n");
	fprintf(stderr, "options:\n");
	fprintf(stderr, "   -s <socket path>     ubus socket\n");
	fprintf(stderr, "   -v,                  debug verbosity; more 'v's mean more verbose\n");
	fprintf(stderr, "   -l,                  log to syslog\n");
	fprintf(stderr, "   -d,                  debug mode; i.e. don't daemonize\n");
	fprintf(stderr, "   -p <pidfile>         pid file path\n");
	fprintf(stderr, "   -o <file>,           log to file\n");
	fprintf(stderr, "   -f,                  treat above file as fifo\n");
	fprintf(stderr, "   -w,                  wait for external trigger\n");
	fprintf(stderr, "\n");
}

static void print_version(void)
{
	fprintf(stdout, "%s: %s-g%s\n", PROG_NAME, verstring, githash);
	fprintf(stdout, "%s: EASYMESH_VERSION %d\n", PROG_NAME, EASYMESH_VERSION);
}

int main(int argc, char **argv)
{
	struct log_options lopts = {
		.logfile = NULL,
		.logfile_isfifo = false,
		.syslogging = false,
		.level = LOGLEVEL_UNSET,
		.features = LOG_FEATURE_ALL,
	};
	struct option lgopts[] = {
		{ "version", 0, 0, 0 },
		{ "help", 0, 0, 0 },
		{ 0, 0, 0, 0 },
	};
	int lidx = 0;

	int ch;

	while ((ch = getopt_long(argc, argv, "hlfdvws:o:p:", lgopts, &lidx)) != -1) {
		switch (ch) {
		case 0:
			switch (lidx) {
			case 0:
				print_version();
				exit(0);
			case 1:
				usage(argv[0]);
				exit(0);
			default:
				break;
			}
			break;
		case 's':
			ubus_socket = optarg;
			break;
		case 'v':
			if (lopts.level < LOGLEVEL_MAX)
				lopts.level++;
			break;
		case 'l':
			lopts.syslogging = true;
			break;
		case 'd':
			daemonize = false;
			break;
		case 'p':
			pidfile = optarg;
			break;
		case 'o':
			lopts.logfile = optarg;
			break;
		case 'f':
			lopts.logfile_isfifo = true;
			break;
		case 'w':
			waitext = true;
			break;
		case 'h':
			usage(argv[0]);
			exit(0);
		default:
			break;
		}
	}

	if (daemonize && !lopts.logfile)
		lopts.syslogging = true;

	if (daemonize)
		do_daemonize(pidfile);

	run_controller(&lopts);

	return 0;
}
