chiark / gitweb /
b07ffa1f2b66edc655d1cf4413ce98b34a7bec71
[disorder] / clients / disorder.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2008 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "common.h"
20
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/un.h>
25 #include <errno.h>
26 #include <locale.h>
27 #include <time.h>
28 #include <stddef.h>
29 #include <unistd.h>
30 #include <pcre.h>
31 #include <ctype.h>
32
33 #include "configuration.h"
34 #include "syscalls.h"
35 #include "log.h"
36 #include "queue.h"
37 #include "client.h"
38 #include "wstat.h"
39 #include "table.h"
40 #include "charset.h"
41 #include "kvp.h"
42 #include "split.h"
43 #include "sink.h"
44 #include "mem.h"
45 #include "defs.h"
46 #include "authorize.h"
47 #include "vector.h"
48 #include "version.h"
49 #include "dateparse.h"
50
51 static disorder_client *client;
52
53 static const struct option options[] = {
54   { "help", no_argument, 0, 'h' },
55   { "version", no_argument, 0, 'V' },
56   { "config", required_argument, 0, 'c' },
57   { "debug", no_argument, 0, 'd' },
58   { "local", no_argument, 0, 'l' },
59   { "no-per-user-config", no_argument, 0, 'N' },
60   { "help-commands", no_argument, 0, 'H' },
61   { "user", required_argument, 0, 'u' },
62   { "password", required_argument, 0, 'p' },
63   { 0, 0, 0, 0 }
64 };
65
66 /* display usage message and terminate */
67 static void help(void) {
68   xprintf("Usage:\n"
69           "  disorder [OPTIONS] COMMAND ...\n"
70           "Options:\n"
71           "  --help, -h              Display usage message\n"
72           "  --help-commands, -H     List commands\n"
73           "  --version, -V           Display version number\n"
74           "  --config PATH, -c PATH  Set configuration file\n"
75           "  --local, -l             Force connection to local server\n"
76           "  --debug, -d             Turn on debugging\n");
77   xfclose(stdout);
78   exit(0);
79 }
80
81 static disorder_client *getclient(void) {
82   if(!client) {
83     if(!(client = disorder_new(1))) exit(EXIT_FAILURE);
84     if(disorder_connect(client)) exit(EXIT_FAILURE);
85   }
86   return client;
87 }
88
89 static void cf_version(char attribute((unused)) **argv) {
90   char *v;
91
92   if(disorder_version(getclient(), &v)) exit(EXIT_FAILURE);
93   xprintf("%s\n", nullcheck(utf82mb(v)));
94 }
95
96 static void print_queue_entry(const struct queue_entry *q) {
97   if(q->track) xprintf("track %s\n", nullcheck(utf82mb(q->track)));
98   if(q->id) xprintf("  id %s\n", nullcheck(utf82mb(q->id)));
99   if(q->submitter) xprintf("  submitted by %s at %s",
100                            nullcheck(utf82mb(q->submitter)), ctime(&q->when));
101   if(q->played) xprintf("  played at %s", ctime(&q->played));
102   if(q->state == playing_started
103      || q->state == playing_paused) xprintf("  %lds so far",  q->sofar);
104   else if(q->expected) xprintf("  might start at %s", ctime(&q->expected));
105   if(q->scratched) xprintf("  scratched by %s\n",
106                            nullcheck(utf82mb(q->scratched)));
107   else xprintf("  %s\n", playing_states[q->state]);
108   if(q->wstat) xprintf("  %s\n", wstat(q->wstat));
109 }
110
111 static void cf_playing(char attribute((unused)) **argv) {
112   struct queue_entry *q;
113
114   if(disorder_playing(getclient(), &q)) exit(EXIT_FAILURE);
115   if(q)
116     print_queue_entry(q);
117   else
118     xprintf("nothing\n");
119 }
120
121 static void cf_play(char **argv) {
122   while(*argv)
123     if(disorder_play(getclient(), *argv++)) exit(EXIT_FAILURE);
124 }
125
126 static void cf_remove(char **argv) {
127   if(disorder_remove(getclient(), argv[0])) exit(EXIT_FAILURE);
128 }
129
130 static void cf_disable(char attribute((unused)) **argv) {
131   if(disorder_disable(getclient())) exit(EXIT_FAILURE);
132 }
133
134 static void cf_enable(char attribute((unused)) **argv) {
135   if(disorder_enable(getclient())) exit(EXIT_FAILURE);
136 }
137
138 static void cf_scratch(char **argv) {
139   if(disorder_scratch(getclient(), argv[0])) exit(EXIT_FAILURE);
140 }
141
142 static void cf_shutdown(char attribute((unused)) **argv) {
143   if(disorder_shutdown(getclient())) exit(EXIT_FAILURE);
144 }
145
146 static void cf_reconfigure(char attribute((unused)) **argv) {
147   /* Re-check configuration for server */
148   if(config_read(1)) fatal(0, "cannot read configuration");
149   if(disorder_reconfigure(getclient())) exit(EXIT_FAILURE);
150 }
151
152 static void cf_rescan(char attribute((unused)) **argv) {
153   if(disorder_rescan(getclient())) exit(EXIT_FAILURE);
154 }
155
156 static void cf_somequeue(int (*fn)(disorder_client *c,
157                                    struct queue_entry **qp)) {
158   struct queue_entry *q;
159
160   if(fn(getclient(), &q)) exit(EXIT_FAILURE);
161   while(q) {
162     print_queue_entry(q);
163     q = q->next;
164   }
165 }
166
167 static void cf_recent(char attribute((unused)) **argv) {
168   cf_somequeue(disorder_recent);
169 }
170
171 static void cf_queue(char attribute((unused)) **argv) {
172   cf_somequeue(disorder_queue);
173 }
174
175 static void cf_quack(char attribute((unused)) **argv) {
176   xprintf("\n"
177           " .------------------.\n"
178           " | Naath is a babe! |\n"
179           " `---------+--------'\n"
180           "            \\\n"
181           "              >0\n"
182           "               (<)'\n"
183           "~~~~~~~~~~~~~~~~~~~~~~\n"
184           "\n");
185 }
186
187 static void cf_somelist(char **argv,
188                         int (*fn)(disorder_client *c,
189                                   const char *arg, const char *re,
190                                   char ***vecp, int *nvecp)) {
191   char **vec;
192   const char *re;
193
194   if(argv[1])
195     re = xstrdup(argv[1] + 1);
196   else
197     re = 0;
198   if(fn(getclient(), argv[0], re, &vec, 0)) exit(EXIT_FAILURE);
199   while(*vec)
200     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
201 }
202
203 static int isarg_regexp(const char *s) {
204   return s[0] == '~';
205 }
206
207 static void cf_dirs(char **argv) {
208   cf_somelist(argv, disorder_directories);
209 }
210
211 static void cf_files(char **argv) {
212   cf_somelist(argv, disorder_files);
213 }
214
215 static void cf_allfiles(char **argv) {
216   cf_somelist(argv, disorder_allfiles);
217 }
218
219 static void cf_get(char **argv) {
220   char *value;
221
222   if(disorder_get(getclient(), argv[0], argv[1], &value)) exit(EXIT_FAILURE);
223   xprintf("%s\n", nullcheck(utf82mb(value)));
224 }
225
226 static void cf_length(char **argv) {
227   long length;
228
229   if(disorder_length(getclient(), argv[0], &length)) exit(EXIT_FAILURE);
230   xprintf("%ld\n", length);
231 }
232
233 static void cf_set(char **argv) {
234   if(disorder_set(getclient(), argv[0], argv[1], argv[2])) exit(EXIT_FAILURE);
235 }
236
237 static void cf_unset(char **argv) {
238   if(disorder_unset(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
239 }
240
241 static void cf_prefs(char **argv) {
242   struct kvp *k;
243
244   if(disorder_prefs(getclient(), argv[0], &k)) exit(EXIT_FAILURE);
245   for(; k; k = k->next)
246     xprintf("%s = %s\n",
247             nullcheck(utf82mb(k->name)), nullcheck(utf82mb(k->value)));
248 }
249
250 static void cf_search(char **argv) {
251   char **results;
252   int nresults, n;
253
254   if(disorder_search(getclient(), *argv, &results, &nresults)) exit(EXIT_FAILURE);
255   for(n = 0; n < nresults; ++n)
256     xprintf("%s\n", nullcheck(utf82mb(results[n])));
257 }
258
259 static void cf_random_disable(char attribute((unused)) **argv) {
260   if(disorder_random_disable(getclient())) exit(EXIT_FAILURE);
261 }
262
263 static void cf_random_enable(char attribute((unused)) **argv) {
264   if(disorder_random_enable(getclient())) exit(EXIT_FAILURE);
265 }
266
267 static void cf_stats(char attribute((unused)) **argv) {
268   char **vec;
269
270   if(disorder_stats(getclient(), &vec, 0)) exit(EXIT_FAILURE);
271   while(*vec)
272       xprintf("%s\n", nullcheck(utf82mb(*vec++)));
273 }
274
275 static void cf_get_volume(char attribute((unused)) **argv) {
276   int l, r;
277
278   if(disorder_get_volume(getclient(), &l, &r)) exit(EXIT_FAILURE);
279   xprintf("%d %d\n", l, r);
280 }
281
282 static void cf_set_volume(char **argv) {
283   if(disorder_set_volume(getclient(), atoi(argv[0]), atoi(argv[1]))) exit(EXIT_FAILURE);
284 }
285
286 static void cf_log(char attribute((unused)) **argv) {
287   if(disorder_log(getclient(), sink_stdio("stdout", stdout))) exit(EXIT_FAILURE);
288 }
289
290 static void cf_move(char **argv) {
291   long n;
292   int e;
293   
294   if((e = xstrtol(&n, argv[1], 0, 10)))
295     fatal(e, "cannot convert '%s'", argv[1]);
296   if(n > INT_MAX || n < INT_MIN)
297     fatal(e, "%ld out of range", n);
298   if(disorder_move(getclient(), argv[0], (int)n)) exit(EXIT_FAILURE);
299 }
300
301 static void cf_part(char **argv) {
302   char *s;
303
304   if(disorder_part(getclient(), &s, argv[0], argv[1], argv[2])) exit(EXIT_FAILURE);
305   xprintf("%s\n", nullcheck(utf82mb(s)));
306 }
307
308 static int isarg_filename(const char *s) {
309   return s[0] == '/';
310 }
311
312 static void cf_authorize(char **argv) {
313   authorize(getclient(), argv[0], argv[1]);
314 }
315
316 static void cf_resolve(char **argv) {
317   char *track;
318
319   if(disorder_resolve(getclient(), &track, argv[0])) exit(EXIT_FAILURE);
320   xprintf("%s\n", nullcheck(utf82mb(track)));
321 }
322
323 static void cf_pause(char attribute((unused)) **argv) {
324   if(disorder_pause(getclient())) exit(EXIT_FAILURE);
325 }
326
327 static void cf_resume(char attribute((unused)) **argv) {
328   if(disorder_resume(getclient())) exit(EXIT_FAILURE);
329 }
330
331 static void cf_tags(char attribute((unused)) **argv) {
332   char **vec;
333
334   if(disorder_tags(getclient(), &vec, 0)) exit(EXIT_FAILURE);
335   while(*vec)
336       xprintf("%s\n", nullcheck(utf82mb(*vec++)));
337 }
338
339 static void cf_users(char attribute((unused)) **argv) {
340   char **vec;
341
342   if(disorder_users(getclient(), &vec, 0)) exit(EXIT_FAILURE);
343   while(*vec)
344     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
345 }
346
347 static void cf_get_global(char **argv) {
348   char *value;
349
350   if(disorder_get_global(getclient(), argv[0], &value)) exit(EXIT_FAILURE);
351   xprintf("%s\n", nullcheck(utf82mb(value)));
352 }
353
354 static void cf_set_global(char **argv) {
355   if(disorder_set_global(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
356 }
357
358 static void cf_unset_global(char **argv) {
359   if(disorder_unset_global(getclient(), argv[0])) exit(EXIT_FAILURE);
360 }
361
362 static int isarg_integer(const char *s) {
363   if(!*s) return 0;
364   while(*s) {
365     if(!isdigit((unsigned char)*s))
366       return 0;
367     ++s;
368   }
369   return 1;
370 }
371
372 static void cf_new(char **argv) {
373   char **vec;
374
375   if(disorder_new_tracks(getclient(), &vec, 0, argv[0] ? atoi(argv[0]) : 0))
376     exit(EXIT_FAILURE);
377   while(*vec)
378     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
379 }
380
381 static void cf_rtp_address(char attribute((unused)) **argv) {
382   char *address, *port;
383
384   if(disorder_rtp_address(getclient(), &address, &port)) exit(EXIT_FAILURE);
385   xprintf("address: %s\nport: %s\n", address, port);
386 }
387
388 static int isarg_rights(const char *arg) {
389   return strchr(arg, ',') || !parse_rights(arg, 0, 0);
390 }
391
392 static void cf_adduser(char **argv) {
393   if(disorder_adduser(getclient(), argv[0], argv[1], argv[2]))
394     exit(EXIT_FAILURE);
395 }
396
397 static void cf_deluser(char **argv) {
398   if(disorder_deluser(getclient(), argv[0]))
399     exit(EXIT_FAILURE);
400 }
401
402 static void cf_edituser(char **argv) {
403   if(disorder_edituser(getclient(), argv[0], argv[1], argv[2]))
404     exit(EXIT_FAILURE);
405 }
406
407 static void cf_userinfo(char **argv) {
408   char *s;
409
410   if(disorder_userinfo(getclient(), argv[0], argv[1], &s))
411     exit(EXIT_FAILURE);
412   xprintf("%s\n", nullcheck(utf82mb(s)));
413 }
414
415 static int isarg_option(const char *arg) {
416   return arg[0] == '-';
417 }
418
419 static int argvlen(char **argv) {
420   char **start = argv;
421   
422   while(*argv)
423     ++argv;
424   return argv - start;
425 }
426
427 static const struct option setup_guest_options[] = {
428   { "help", no_argument, 0, 'h' },
429   { "online-registration", no_argument, 0, 'r' },
430   { "no-online-registration", no_argument, 0, 'R' },
431   { 0, 0, 0, 0 }
432 };
433
434 static void help_setup_guest(void) {
435   xprintf("Usage:\n"
436           "  disorder setup-guest [OPTIONS]\n"
437           "Options:\n"
438           "  --help, -h                Display usage message\n"
439           "  --online-registration     Enable online registration (default)\n"
440           "  --no-online-registration  Disable online registration\n");
441   xfclose(stdout);
442   exit(0);
443 }
444
445 static void cf_setup_guest(char **argv) {
446   int n, online_registration = 1;
447   
448   while((n = getopt_long(argvlen(argv) + 1, argv - 1,
449                          "hrR", setup_guest_options, 0)) >= 0) {
450     switch(n) {
451     case 'h': help_setup_guest();
452     case 'r': online_registration = 1; break;
453     case 'R': online_registration = 0; break;
454     default: fatal(0, "invalid option");
455     }
456   }
457   if(online_registration && !config->mail_sender)
458     fatal(0, "you MUST set mail_sender if you want online registration");
459   if(disorder_adduser(getclient(), "guest", "",
460                       online_registration ? "read,register" : "read"))
461     exit(EXIT_FAILURE);
462 }
463
464 struct scheduled_event {
465   time_t when;
466   struct kvp *actiondata;
467   char *id;
468 };
469
470 static int compare_event(const void *av, const void *bv) {
471   struct scheduled_event *a = (void *)av, *b = (void *)bv;
472
473   /* Primary sort key is the trigger time */
474   if(a->when < b->when)
475     return -1;
476   else if(a->when > b->when)
477     return 1;
478   /* For events that go off at the same time just sort by ID */
479   return strcmp(a->id, b->id);
480 }
481
482 static void cf_schedule_list(char attribute((unused)) **argv) {
483   char **ids;
484   int nids, n;
485   struct scheduled_event *events;
486   char tb[128];
487   const char *action, *key, *value, *priority;
488   int prichar;
489
490   /* Get all known events */
491   if(disorder_schedule_list(getclient(), &ids, &nids))
492     exit(EXIT_FAILURE);
493   events = xcalloc(nids, sizeof *events);
494   for(n = 0; n < nids; ++n) {
495     events[n].id = ids[n];
496     if(disorder_schedule_get(getclient(), ids[n], &events[n].actiondata))
497       exit(EXIT_FAILURE);
498     events[n].when = atoll(kvp_get(events[n].actiondata, "when"));
499   }
500   /* Sort by trigger time */
501   qsort(events, nids, sizeof *events, compare_event);
502   /* Display them */
503   for(n = 0; n < nids; ++n) {
504     strftime(tb, sizeof tb, "%Y-%m-%d %H:%M:%S %Z", localtime(&events[n].when));
505     action = kvp_get(events[n].actiondata, "action");
506     priority = kvp_get(events[n].actiondata, "priority");
507     if(!strcmp(priority, "junk"))
508       prichar = 'J';
509     else if(!strcmp(priority, "normal"))
510       prichar = 'N';
511     else
512       prichar = '?';
513     xprintf("%11s %-25s %c %-8s %s",
514             events[n].id, tb, prichar, kvp_get(events[n].actiondata, "who"),
515             action);
516     if(!strcmp(action, "play"))
517       xprintf(" %s",
518               nullcheck(utf82mb(kvp_get(events[n].actiondata, "track"))));
519     else if(!strcmp(action, "set-global")) {
520       key = kvp_get(events[n].actiondata, "key");
521       value = kvp_get(events[n].actiondata, "value");
522       if(value)
523         xprintf(" %s=%s",
524                 nullcheck(utf82mb(key)),
525                 nullcheck(utf82mb(value)));
526       else
527         xprintf(" %s unset",
528                 nullcheck(utf82mb(key)));
529     }
530     xprintf("\n");
531   }
532 }
533
534 static void cf_schedule_del(char **argv) {
535   if(disorder_schedule_del(getclient(), argv[0]))
536     exit(EXIT_FAILURE);
537 }
538
539 static void cf_schedule_play(char **argv) {
540   if(disorder_schedule_add(getclient(),
541                            dateparse(argv[0]),
542                            argv[1],
543                            "play",
544                            argv[2]))
545     exit(EXIT_FAILURE);
546 }
547
548 static void cf_schedule_set_global(char **argv) {
549   if(disorder_schedule_add(getclient(),
550                            dateparse(argv[0]),
551                            argv[1],
552                            "set-global",
553                            argv[2],
554                            argv[3]))
555     exit(EXIT_FAILURE);
556 }
557
558 static void cf_schedule_unset_global(char **argv) {
559   if(disorder_schedule_add(getclient(),
560                            dateparse(argv[0]),
561                            argv[1],
562                            "set-global",
563                            argv[2],
564                            (char *)0))
565     exit(EXIT_FAILURE);
566 }
567
568 static const struct command {
569   const char *name;
570   int min, max;
571   void (*fn)(char **);
572   int (*isarg)(const char *);
573   const char *argstr, *desc;
574 } commands[] = {
575   { "adduser",        2, 3, cf_adduser, isarg_rights, "USERNAME PASSWORD [RIGHTS]",
576                       "Create a new user" },
577   { "allfiles",       1, 2, cf_allfiles, isarg_regexp, "DIR [~REGEXP]",
578                       "List all files and directories in DIR" },
579   { "authorize",      1, 2, cf_authorize, isarg_rights, "USERNAME [RIGHTS]",
580                       "Authorize user USERNAME to connect" },
581   { "deluser",        1, 1, cf_deluser, 0, "USERNAME",
582                       "Delete user USERNAME" },
583   { "dirs",           1, 2, cf_dirs, isarg_regexp, "DIR [~REGEXP]",
584                       "List directories in DIR" },
585   { "disable",        0, 0, cf_disable, 0, "",
586                       "Disable play" },
587   { "disable-random", 0, 0, cf_random_disable, 0, "",
588                       "Disable random play" },
589   { "edituser",       3, 3, cf_edituser, 0, "USERNAME PROPERTY VALUE",
590                       "Set a property of user USERNAME" },
591   { "enable",         0, 0, cf_enable, 0, "",
592                       "Enable play" },
593   { "enable-random",  0, 0, cf_random_enable, 0, "",
594                       "Enable random play" },
595   { "files",          1, 2, cf_files, isarg_regexp, "DIR [~REGEXP]",
596                       "List files in DIR" },
597   { "get",            2, 2, cf_get, 0, "TRACK NAME",
598                       "Get a preference value" },
599   { "get-global",     1, 1, cf_get_global, 0, "NAME",
600                       "Get a global preference value" },
601   { "get-volume",     0, 0, cf_get_volume, 0, "",
602                       "Get the current volume" },
603   { "length",         1, 1, cf_length, 0, "TRACK",
604                       "Get the length of TRACK in seconds" },
605   { "log",            0, 0, cf_log, 0, "",
606                       "Copy event log to stdout" },
607   { "move",           2, 2, cf_move, 0, "TRACK DELTA",
608                       "Move a track in the queue" },
609   { "new",            0, 1, cf_new, isarg_integer, "[MAX]",
610                       "Get the most recently added MAX tracks" },
611   { "part",           3, 3, cf_part, 0, "TRACK CONTEXT PART",
612                       "Find a track name part" },
613   { "pause",          0, 0, cf_pause, 0, "",
614                       "Pause the currently playing track" },
615   { "play",           1, INT_MAX, cf_play, isarg_filename, "TRACKS...",
616                       "Add TRACKS to the end of the queue" },
617   { "playing",        0, 0, cf_playing, 0, "",
618                       "Report the playing track" },
619   { "prefs",          1, 1, cf_prefs, 0, "TRACK",
620                       "Display all the preferences for TRACK" },
621   { "quack",          0, 0, cf_quack, 0, 0, 0 },
622   { "queue",          0, 0, cf_queue, 0, "",
623                       "Display the current queue" },
624   { "random-disable", 0, 0, cf_random_disable, 0, "",
625                       "Disable random play" },
626   { "random-enable",  0, 0, cf_random_enable, 0, "",
627                       "Enable random play" },
628   { "recent",         0, 0, cf_recent, 0, "",
629                       "Display recently played track" },
630   { "reconfigure",    0, 0, cf_reconfigure, 0, "",
631                       "Reconfigure the daemon" },
632   { "remove",         1, 1, cf_remove, 0, "TRACK",
633                       "Remove a track from the queue" },
634   { "rescan",         0, 0, cf_rescan, 0, "",
635                       "Rescan for new tracks" },
636   { "resolve",        1, 1, cf_resolve, 0, "TRACK",
637                       "Resolve alias for TRACK" },
638   { "resume",         0, 0, cf_resume, 0, "",
639                       "Resume after a pause" },
640   { "rtp-address",    0, 0, cf_rtp_address, 0, "",
641                       "Report server's broadcast address" },
642   { "schedule-del",   1, 1, cf_schedule_del, 0, "EVENT",
643                       "Delete a scheduled event" },
644   { "schedule-list",  0, 0, cf_schedule_list, 0, "",
645                       "List scheduled events" },
646   { "schedule-play",  3, 3, cf_schedule_play, 0, "WHEN PRI TRACK",
647                       "Play TRACK later" },
648   { "schedule-set-global", 4, 4, cf_schedule_set_global, 0, "WHEN PRI NAME VAL",
649                       "Set a global preference later" },
650   { "schedule-unset-global", 3, 3, cf_schedule_unset_global, 0, "WHEN PRI NAME",
651                       "Unset a global preference later" },
652   { "scratch",        0, 0, cf_scratch, 0, "",
653                       "Scratch the currently playing track" },
654   { "scratch-id",     1, 1, cf_scratch, 0, "ID",
655                       "Scratch the currently playing track" },
656   { "search",         1, 1, cf_search, 0, "WORDS",
657                       "Display tracks matching all the words" },
658   { "set",            3, 3, cf_set, 0, "TRACK NAME VALUE",
659                       "Set a preference value" },
660   { "set-global",     2, 2, cf_set_global, 0, "NAME VALUE",
661                       "Set a global preference value" },
662   { "set-volume",     2, 2, cf_set_volume, 0, "LEFT RIGHT",
663                       "Set the volume" },
664   { "setup-guest",    0, INT_MAX, cf_setup_guest, isarg_option, "[OPTIONS]",
665                       "Create the guest login" },
666   { "shutdown",       0, 0, cf_shutdown, 0, "",
667                       "Shut down the daemon" },
668   { "stats",          0, 0, cf_stats, 0, "",
669                       "Display server statistics" },
670   { "tags",           0, 0, cf_tags, 0, "",
671                       "List known tags" },
672   { "unset",          2, 2, cf_unset, 0, "TRACK NAME",
673                       "Unset a preference" },
674   { "unset-global",   1, 1, cf_unset_global, 0, "NAME",
675                       "Unset a global preference" },
676   { "userinfo",       2, 2, cf_userinfo, 0, "USERNAME PROPERTY",
677                       "Get a property of a user" },
678   { "users",          0, 0, cf_users, 0, "",
679                       "List all users" },
680   { "version",        0, 0, cf_version, 0, "",
681                       "Display the server version" },
682 };
683
684 static void help_commands(void) {
685   unsigned n, max = 0, l;
686
687   xprintf("Command summary:\n");
688   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
689     if(!commands[n].desc) continue;
690     l = strlen(commands[n].name);
691     if(*commands[n].argstr)
692       l += strlen(commands[n].argstr) + 1;
693     if(l > max)
694       max = l;
695   }
696   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
697     if(!commands[n].desc) continue;
698     l = strlen(commands[n].name);
699     if(*commands[n].argstr)
700       l += strlen(commands[n].argstr) + 1;
701     xprintf("  %s%s%s%*s  %s\n", commands[n].name,
702             *commands[n].argstr ? " " : "",
703             commands[n].argstr,
704             max - l, "",
705             commands[n].desc);
706   }
707   xfclose(stdout);
708   exit(0);
709 }
710
711 int main(int argc, char **argv) {
712   int n, i, j, local = 0;
713   int status = 0;
714   struct vector args;
715   const char *user = 0, *password = 0;
716
717   mem_init();
718   /* garbage-collect PCRE's memory */
719   pcre_malloc = xmalloc;
720   pcre_free = xfree;
721   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
722   if(!setlocale(LC_TIME, "")) fatal(errno, "error calling setlocale");
723   while((n = getopt_long(argc, argv, "+hVc:dHlNu:p:", options, 0)) >= 0) {
724     switch(n) {
725     case 'h': help();
726     case 'H': help_commands();
727     case 'V': version("disorder");
728     case 'c': configfile = optarg; break;
729     case 'd': debugging = 1; break;
730     case 'l': local = 1; break;
731     case 'N': config_per_user = 0; break;
732     case 'u': user = optarg; break;
733     case 'p': password = optarg; break;
734     default: fatal(0, "invalid option");
735     }
736   }
737   if(config_read(0)) fatal(0, "cannot read configuration");
738   if(user) {
739     config->username = user;
740     config->password = 0;
741   }
742   if(password)
743     config->password = password;
744   if(local)
745     config->connect.n = 0;
746   n = optind;
747   optind = 1;                           /* for subsequent getopt calls */
748   /* accumulate command args */
749   while(n < argc) {
750     if((i = TABLE_FIND(commands, name, argv[n])) < 0)
751       fatal(0, "unknown command '%s'", argv[n]);
752     if(n + commands[i].min >= argc)
753       fatal(0, "missing arguments to '%s'", argv[n]);
754     vector_init(&args);
755     /* Include the command name in the args, but at element -1, for
756      * the benefit of subcommand getopt calls */
757     vector_append(&args, argv[n]);
758     n++;
759     for(j = 0; j < commands[i].min; ++j)
760       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
761     for(; j < commands[i].max
762           && n + j < argc
763           && commands[i].isarg(argv[n + j]); ++j)
764       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
765     vector_terminate(&args);
766     commands[i].fn(args.vec + 1);
767     n += j;
768   }
769   if(client && disorder_close(client)) exit(EXIT_FAILURE);
770   if(fclose(stdout) < 0) fatal(errno, "error closing stdout");
771   return status;
772 }
773
774 /*
775 Local Variables:
776 c-basic-offset:2
777 comment-column:40
778 End:
779 */