summaryrefslogtreecommitdiff
path: root/src/main.c
blob: ffae6e2fdb20cbf078a062906457267f094600cf (plain)
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
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include "data_store.h"
#include "game.h"
#include "manual.h"

#define DEFAULT_PORT "12345"

/**
 * Print usage information
 * @param[in] name The name of the program (normally argv[0])
 */
static void print_usage(const char* name)
{
	const char* usage = "Usage: %s [-u username] [-s address] [-n num_players] [-l] [-p port] [-m]\n"
	                    "\t-s address\t\thostname/address to connect to (client, required) or listen on (server, optional)\n"
			    "\t-n num_players\t\tnumber of players; only on server (default: 2, max: 10)\n"
			    "\t-l\t\t\tstart server\n"
			    "\t-u username\t\tyour nickname in the player list (default: $USER)\n"
			    "\t-p port\t\t\tport to use for connecting/listening (default: %s)\n"
			    "\t-m\t\t\tdisplay the manual\n";

	fprintf(stderr, usage, name, DEFAULT_PORT);
	exit(EXIT_FAILURE);
}

/**
 * The application's entry point.
 * @param[in] argc The number of arguments passed
 * @param[in] argv The array of passed arguments
*/
int main(int argc, char *argv[])
{
	int opt;
	uint8_t num_players = 2;
	char* port = NULL;
	char* addr = NULL;
	bool servermode = false;
	data_store_t *ds = data_store();

	const char* accepted = "u:s:p:n:hlm";
	while((opt = getopt(argc, argv, accepted)) != -1)
	{
		switch(opt)
		{
			case 'u': // nickname
				strncpy(ds->nickname, optarg, MAX_PLAYER_NAME_LENGTH);
				ds->nickname[MAX_PLAYER_NAME_LENGTH] = '\0';
				break;
			case 'p': // port
				port = optarg;
				break;
			case 's': // hostname
				addr = optarg;
				break;
			case 'n': // number of users
				num_players = atoi(optarg);
				break;
			case 'l':
				servermode = true;
				break;
			case 'm':
				print_manual();
				break;
			case 'h': // help
			default:
				print_usage(argv[0]);
				break;
		}
	}

	if(!servermode && addr == NULL)
		print_usage(argv[0]);

	if(port == NULL)
		port = DEFAULT_PORT;

	if(strlen(ds->nickname) == 0)
	{
		const char* env_nick = getenv("USER");
		strncpy(ds->nickname, (env_nick!=NULL)?env_nick:"hornoxe", MAX_PLAYER_NAME_LENGTH);
		ds->nickname[MAX_PLAYER_NAME_LENGTH] = '\0';
	}

	start_game(servermode, addr, port, num_players);

	exit(EXIT_SUCCESS);
}