aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/worker_main.c
blob: d88071da9b03f68f85bf5cf4c2722b425d726548 (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
#include "const.h"
#include "worker.h"

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>

static struct settings default_settings()
{
	struct settings settings = {DEFAULT_HOST, DEFAULT_PORT};
	return settings;
}

static void print_usage(const char *argv0)
{
	printf("usage: %s [-h|--help] [-V|--version] [-H|--host HOST] [-p|--port PORT]\n", argv0);
}

static void print_version()
{
	printf("%s\n", VERSION);
}

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

	*settings = default_settings();

	static struct option long_options[] = {
	    {"help", no_argument, 0, 'h'},
	    {"version", no_argument, 0, 'V'},
	    {"host", required_argument, 0, 'H'},
	    {"port", required_argument, 0, 'p'},
	    {0, 0, 0, 0},
	};

	while ((opt = getopt_long(argc, argv, "hVH:p:", long_options, &longind)) != -1) {
		switch (opt) {
		case 'h':
			print_usage(argv[0]);
			exit(0);
			break;
		case 'V':
			print_version();
			exit(0);
			break;
		case 'H':
			settings->host = optarg;
			break;
		case 'p':
			settings->port = optarg;
			break;
		default:
			print_usage(argv[0]);
			exit(1);
			break;
		}
	}

	return 0;
}

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

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

	ret = worker_create(&worker, &settings);
	if (ret < 0)
		return ret;

	ret = worker_main(&worker, argc - optind, argv + optind);
	if (ret < 0)
		goto destroy_worker;

destroy_worker:
	worker_destroy(&worker);

	return ret;
}