aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/server_main.c
blob: d00097266223ff3228c62a7b2ca6a2a051e462e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 * Copyright (c) 2022 Egor Tensin <egor@tensin.name>
 * This file is part of the "cimple" project.
 * For details, see https://github.com/egor-tensin/cimple.
 * Distributed under the MIT License.
 */

#include "cmd_line.h"
#include "const.h"
#include "log.h"
#include "server.h"

#include <getopt.h>
#include <unistd.h>

static struct settings default_settings(void)
{
	struct settings settings = {
	    .port = default_port,
	    .sqlite_path = default_sqlite_path,
	};
	return settings;
}

const char *get_usage_string(void)
{
	return "[-h|--help] [-V|--version] [-v|--verbose] [-p|--port PORT] [-s|--sqlite PATH]";
}

static int parse_settings(struct settings *settings, int argc, char *argv[])
{
	int opt, longind;

	*settings = default_settings();

	/* clang-format off */
	static struct option long_options[] = {
	    {"help", no_argument, 0, 'h'},
	    {"version", no_argument, 0, 'V'},
	    {"verbose", no_argument, 0, 'v'},
	    {"port", required_argument, 0, 'p'},
	    {"sqlite", required_argument, 0, 's'},
	    {0, 0, 0, 0},
	};
	/* clang-format on */

	while ((opt = getopt_long(argc, argv, "hVvp:s:", long_options, &longind)) != -1) {
		switch (opt) {
		case 'h':
			exit_with_usage(0);
			break;
		case 'V':
			exit_with_version();
			break;
		case 'v':
			g_log_lvl = LOG_LVL_DEBUG;
			break;
		case 'p':
			settings->port = optarg;
			break;
		case 's':
			settings->sqlite_path = optarg;
			break;
		default:
			exit_with_usage(1);
			break;
		}
	}

	return 0;
}

int main(int argc, char *argv[])
{
	struct settings settings;
	struct server *server = NULL;
	int ret = 0;

	ret = parse_settings(&settings, argc, argv);
	if (ret < 0)
		return ret;

	ret = server_create(&server, &settings);
	if (ret < 0)
		return ret;

	ret = server_main(server);
	if (ret < 0)
		goto destroy_server;

destroy_server:
	server_destroy(server);

	return ret;
}