25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
26 * POSSIBILITY OF SUCH DAMAGE. |
26 * POSSIBILITY OF SUCH DAMAGE. |
27 * |
27 * |
28 */ |
28 */ |
29 |
29 |
30 #include <stdlib.h> |
30 #include "terminal-chess.h" |
|
31 #include <string.h> |
|
32 |
|
33 int get_settings(int argc, char **argv, Settings *settings) { |
|
34 char *valid; |
|
35 |
|
36 for (char opt ; (opt = getopt(argc, argv, "hp:")) != -1 ;) { |
|
37 switch (opt) { |
|
38 case 'p': |
|
39 if (strtol(optarg, &valid, 10) < 1025 || *valid != '\0') { |
|
40 fprintf(stderr, |
|
41 "Invalid port number (%s) - choose a number > 1024\n", |
|
42 optarg); |
|
43 return 1; |
|
44 } else { |
|
45 settings->port = optarg; |
|
46 } |
|
47 break; |
|
48 case 'h': |
|
49 case '?': |
|
50 settings->printhelp = 1; |
|
51 break; |
|
52 } |
|
53 } |
|
54 |
|
55 if (optind == argc - 1) { |
|
56 settings->serverhost = argv[optind]; |
|
57 } else if (optind < argc - 1) { |
|
58 fprintf(stderr, "Too many arguments\n"); |
|
59 return 1; |
|
60 } |
|
61 |
|
62 return 0; |
|
63 } |
|
64 |
|
65 Settings default_settings() { |
|
66 Settings settings; |
|
67 memset(&settings, 0, sizeof(Settings)); |
|
68 settings.port = "27015"; |
|
69 return settings; |
|
70 } |
|
71 |
|
72 int cleanup(Settings *settings, int exitcode) { |
|
73 if (settings->server) { |
|
74 if (net_destroy(settings->server)) { |
|
75 perror("Server shutdown failed"); |
|
76 } |
|
77 } |
|
78 |
|
79 return exitcode; |
|
80 } |
31 |
81 |
32 int main(int argc, char **argv) { |
82 int main(int argc, char **argv) { |
33 return EXIT_SUCCESS; |
83 |
|
84 Settings settings = default_settings(); |
|
85 get_settings(argc, argv, &settings); |
|
86 |
|
87 if (settings.printhelp) { |
|
88 printf( |
|
89 "Usage: %s [OPTION]... [HOST]\n" |
|
90 "Starts/joins a network chess game\n\n" |
|
91 " -h This help page\n" |
|
92 " -p TCP port to use (default: 27015)\n", |
|
93 argv[0]); |
|
94 return EXIT_SUCCESS; |
|
95 } |
|
96 |
|
97 Server server; |
|
98 settings.server = &server; |
|
99 |
|
100 if (is_server(&settings)) { |
|
101 if (net_find(&server, settings.serverhost, settings.port)) { |
|
102 perror("Can't find server"); |
|
103 return cleanup(&settings, EXIT_FAILURE); |
|
104 } |
|
105 |
|
106 if (net_connect(&server)) { |
|
107 perror("Can't connect to server"); |
|
108 return cleanup(&settings, EXIT_FAILURE); |
|
109 } |
|
110 } else { |
|
111 if (net_create(&server, settings.port)) { |
|
112 perror("Server creation failed"); |
|
113 return cleanup(&settings, EXIT_FAILURE); |
|
114 } |
|
115 |
|
116 if (net_listen(&server)) { |
|
117 perror("Listening for client failed"); |
|
118 return cleanup(&settings, EXIT_FAILURE); |
|
119 } |
|
120 } |
|
121 |
|
122 return cleanup(&settings, EXIT_SUCCESS); |
34 } |
123 } |
35 |
124 |