/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * main.c - WiFi manager main
 *
 * Copyright (C) 2019-2024 iopsys Software Solutions AB. All rights reserved.
 * Copyright (C) 2025 Genexis AB.
 *
 * Author: Anjan Chanda <anjan.chanda@genexis.eu>
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <json-c/json.h>
#include <libubox/blobmsg.h>
#include <libubox/blobmsg_json.h>
#include <libubox/uloop.h>
#include <libubox/ustream.h>
#include <libubox/utils.h>
#include <libubus.h>

#include <easy/easy.h>
#include <wifi.h>
#include "wifimngr.h"
#include "debug.h"

const char *PROG_NAME = "wifimngr";

static void usage(void)
{
	fprintf(stderr, "Usage: %s [options]\n", PROG_NAME);
	fprintf(stderr, "\n");
	fprintf(stderr, "options:\n");
	fprintf(stderr, "   -h               usage\n");
	fprintf(stderr, "   -v               print version\n");
	fprintf(stderr, "   -s <socket path> UBUS socket path (default: NULL)\n");
	fprintf(stderr, "   -c <conf-file>   specify configuration file (default: /etc/config/wireless)\n");
	fprintf(stderr, "   -d               debug level; more 'd's mean more verbose (default: LOG_INFO)\n");
	fprintf(stderr, "   -l               log to system log\n");
	fprintf(stderr, "   -o <file>        log to file\n");
	fprintf(stderr, "   -f               treat above logfile as fifo (for rolling logs)\n");
	fprintf(stderr, "\n");
}


int main(int argc, char **argv)
{
	struct wifimngr_cmdline_opts opts = {
		.ubus_socket = NULL,
		.evmap_file = DEFAULT_WIFI_EVMAP_JSON_FILE,
		.conffile = DEFAULT_WIFI_CONFFILE,
		.loglevel = DEFAULT_LOGLEVEL,
		.features = LOG_FEATURE_ALL,
		.syslogging = false,
		.logfile = NULL,
		.logfile_isfifo = false,
#if defined(WIFIMNGR_BUILD_TR181_PLUGIN) && defined(HAS_UBUS)
		.dm_type = 0
#endif
	};
	int ch;

	while ((ch = getopt(argc, argv, "vhc:ds:e:o:flp")) != -1) {
		switch (ch) {
		case 'v':
			wifimngr_version();
			exit(0);
		case 'h':
			usage();
			exit(0);
		case 'c':
			opts.conffile = optarg;
			break;
		case 'd':
			opts.loglevel++;
			break;
		case 's':
			opts.ubus_socket = optarg;
			break;
		case 'e':
			opts.evmap_file = optarg;
			break;
		case 'o':
			opts.logfile = optarg;
			break;
		case 'f':
			opts.logfile_isfifo = true;
			break;
		case 'l':
			opts.syslogging = true;
			break;
		case 'p':
#if defined(WIFIMNGR_BUILD_TR181_PLUGIN) && defined(HAS_UBUS)
			opts.dm_type++;
#endif
			break;
		default:
			break;
		}
	}

	wifimngr_main(&opts);

	return 0;
}
