chiark / gitweb /
protogen: disorder_new_tracks().
[disorder] / clients / disorder.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2009 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 /** @file clients/disorder.c
19  * @brief Command-line client
20  */
21
22 #include "common.h"
23
24 #include <getopt.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <errno.h>
29 #include <locale.h>
30 #include <time.h>
31 #include <stddef.h>
32 #include <unistd.h>
33 #include <pcre.h>
34 #include <ctype.h>
35 #include <gcrypt.h>
36 #include <langinfo.h>
37
38 #include "configuration.h"
39 #include "syscalls.h"
40 #include "log.h"
41 #include "queue.h"
42 #include "client.h"
43 #include "wstat.h"
44 #include "table.h"
45 #include "charset.h"
46 #include "kvp.h"
47 #include "split.h"
48 #include "sink.h"
49 #include "mem.h"
50 #include "defs.h"
51 #include "authorize.h"
52 #include "vector.h"
53 #include "version.h"
54 #include "dateparse.h"
55 #include "trackdb.h"
56 #include "inputline.h"
57
58 static disorder_client *client;
59
60 static const struct option options[] = {
61   { "help", no_argument, 0, 'h' },
62   { "version", no_argument, 0, 'V' },
63   { "config", required_argument, 0, 'c' },
64   { "debug", no_argument, 0, 'd' },
65   { "local", no_argument, 0, 'l' },
66   { "no-per-user-config", no_argument, 0, 'N' },
67   { "help-commands", no_argument, 0, 'H' },
68   { "user", required_argument, 0, 'u' },
69   { "password", required_argument, 0, 'p' },
70   { "wait-for-root", no_argument, 0, 'W' },
71   { 0, 0, 0, 0 }
72 };
73
74 /* display usage message and terminate */
75 static void help(void) {
76   xprintf("Usage:\n"
77           "  disorder [OPTIONS] COMMAND ...\n"
78           "Options:\n"
79           "  --help, -h              Display usage message\n"
80           "  --help-commands, -H     List commands\n"
81           "  --version, -V           Display version number\n"
82           "  --config PATH, -c PATH  Set configuration file\n"
83           "  --local, -l             Force connection to local server\n"
84           "  --debug, -d             Turn on debugging\n");
85   xfclose(stdout);
86   exit(0);
87 }
88
89 static disorder_client *getclient(void) {
90   if(!client) {
91     if(!(client = disorder_new(1))) exit(EXIT_FAILURE);
92     if(disorder_connect(client)) exit(EXIT_FAILURE);
93   }
94   return client;
95 }
96
97 static void cf_version(char attribute((unused)) **argv) {
98   char *v;
99
100   if(disorder_version(getclient(), &v)) exit(EXIT_FAILURE);
101   v = nullcheck(utf82mb_f(v));
102   xprintf("%s\n", v);
103   xfree(v);
104 }
105
106 static void print_queue_entry(const struct queue_entry *q) {
107   if(q->track) xprintf("track %s\n", nullcheck(utf82mb(q->track)));
108   if(q->id) xprintf("  id %s\n", nullcheck(utf82mb(q->id)));
109   switch(q->origin) {
110   case origin_adopted:
111   case origin_picked:
112   case origin_scheduled:
113     xprintf("  %s by %s at %s",
114             track_origins[q->origin],
115             nullcheck(utf82mb(q->submitter)), ctime(&q->when));
116     break;
117   default:
118     break;
119   }
120   if(q->played) xprintf("  played at %s", ctime(&q->played));
121   if(q->state == playing_started
122      || q->state == playing_paused) xprintf("  %lds so far",  q->sofar);
123   else if(q->expected) xprintf("  might start at %s", ctime(&q->expected));
124   if(q->scratched) xprintf("  scratched by %s\n",
125                            nullcheck(utf82mb(q->scratched)));
126   else xprintf("  %s\n", playing_states[q->state]);
127   if(q->wstat) xprintf("  %s\n", wstat(q->wstat));
128 }
129
130 static void cf_playing(char attribute((unused)) **argv) {
131   struct queue_entry *q;
132
133   if(disorder_playing(getclient(), &q)) exit(EXIT_FAILURE);
134   if(q)
135     print_queue_entry(q);
136   else
137     xprintf("nothing\n");
138 }
139
140 static void cf_play(char **argv) {
141   char *id;
142   while(*argv)
143     if(disorder_play(getclient(), *argv++, &id)) exit(EXIT_FAILURE);
144 }
145
146 static void cf_remove(char **argv) {
147   if(disorder_remove(getclient(), argv[0])) exit(EXIT_FAILURE);
148 }
149
150 static void cf_disable(char attribute((unused)) **argv) {
151   if(disorder_disable(getclient())) exit(EXIT_FAILURE);
152 }
153
154 static void cf_enable(char attribute((unused)) **argv) {
155   if(disorder_enable(getclient())) exit(EXIT_FAILURE);
156 }
157
158 static void cf_scratch(char **argv) {
159   if(disorder_scratch(getclient(), argv[0])) exit(EXIT_FAILURE);
160 }
161
162 static void cf_shutdown(char attribute((unused)) **argv) {
163   if(disorder_shutdown(getclient())) exit(EXIT_FAILURE);
164 }
165
166 static void cf_reconfigure(char attribute((unused)) **argv) {
167   /* Re-check configuration for server */
168   if(config_read(1, NULL))
169     disorder_fatal(0, "cannot read configuration");
170   if(disorder_reconfigure(getclient())) exit(EXIT_FAILURE);
171 }
172
173 static void cf_rescan(char attribute((unused)) **argv) {
174   if(disorder_rescan(getclient())) exit(EXIT_FAILURE);
175 }
176
177 static void cf_somequeue(int (*fn)(disorder_client *c,
178                                    struct queue_entry **qp)) {
179   struct queue_entry *q, *qbase;
180
181   if(fn(getclient(), &qbase)) exit(EXIT_FAILURE);
182   for(q = qbase; q; q = q->next)
183     print_queue_entry(q);
184   queue_free(qbase, 1);
185 }
186
187 static void cf_recent(char attribute((unused)) **argv) {
188   cf_somequeue(disorder_recent);
189 }
190
191 static void cf_queue(char attribute((unused)) **argv) {
192   cf_somequeue(disorder_queue);
193 }
194
195 static void cf_quack(char attribute((unused)) **argv) {
196   if(!strcasecmp(nl_langinfo(CODESET), "utf-8")) {
197 #define TL "\xE2\x95\xAD"
198 #define TR "\xE2\x95\xAE"
199 #define BR "\xE2\x95\xAF"
200 #define BL "\xE2\x95\xB0"
201 #define H "\xE2\x94\x80"
202 #define V "\xE2\x94\x82"
203 #define T "\xE2\x94\xAC"
204     xprintf("\n"
205             " "TL H H H H H H H H H H H H H H H H H H TR"\n"
206             " "V" Naath is a babe! "V"\n"
207             " "BL H H H H H H H H H T H H H H H H H H BR"\n"
208             "            \\\n"
209             "              >0\n"
210             "               (<)'\n"
211             "~~~~~~~~~~~~~~~~~~~~~~\n"
212             "\n");
213   } else {
214     xprintf("\n"
215             " .------------------.\n"
216             " | Naath is a babe! |\n"
217             " `---------+--------'\n"
218             "            \\\n"
219             "              >0\n"
220             "               (<)'\n"
221             "~~~~~~~~~~~~~~~~~~~~~~\n"
222             "\n");
223   }
224 }
225
226 static void cf_somelist(char **argv,
227                         int (*fn)(disorder_client *c,
228                                   const char *arg, const char *re,
229                                   char ***vecp, int *nvecp)) {
230   char **vec, **base;
231   const char *re;
232
233   if(argv[1])
234     re = xstrdup(argv[1] + 1);
235   else
236     re = 0;
237   if(fn(getclient(), argv[0], re, &base, 0)) exit(EXIT_FAILURE);
238   for(vec = base; *vec; ++vec)
239     xprintf("%s\n", nullcheck(utf82mb_f(*vec)));
240   xfree(base);
241 }
242
243 static int isarg_regexp(const char *s) {
244   return s[0] == '~';
245 }
246
247 static void cf_dirs(char **argv) {
248   cf_somelist(argv, disorder_dirs);
249 }
250
251 static void cf_files(char **argv) {
252   cf_somelist(argv, disorder_files);
253 }
254
255 static void cf_allfiles(char **argv) {
256   cf_somelist(argv, disorder_allfiles);
257 }
258
259 static void cf_get(char **argv) {
260   char *value;
261
262   if(disorder_get(getclient(), argv[0], argv[1], &value)) exit(EXIT_FAILURE);
263   xprintf("%s\n", nullcheck(utf82mb_f(value)));
264 }
265
266 static void cf_length(char **argv) {
267   long length;
268
269   if(disorder_length(getclient(), argv[0], &length)) exit(EXIT_FAILURE);
270   xprintf("%ld\n", length);
271 }
272
273 static void cf_set(char **argv) {
274   if(disorder_set(getclient(), argv[0], argv[1], argv[2])) exit(EXIT_FAILURE);
275 }
276
277 static void cf_unset(char **argv) {
278   if(disorder_unset(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
279 }
280
281 static void cf_prefs(char **argv) {
282   struct kvp *k, *base;
283
284   if(disorder_prefs(getclient(), argv[0], &base)) exit(EXIT_FAILURE);
285   for(k = base; k; k = k->next)
286     xprintf("%s = %s\n",
287             nullcheck(utf82mb(k->name)), nullcheck(utf82mb(k->value)));
288   kvp_free(base);
289 }
290
291 static void cf_search(char **argv) {
292   char **results;
293   int nresults, n;
294
295   if(disorder_search(getclient(), *argv, &results, &nresults)) exit(EXIT_FAILURE);
296   for(n = 0; n < nresults; ++n)
297     xprintf("%s\n", nullcheck(utf82mb(results[n])));
298   free_strings(nresults, results);
299 }
300
301 static void cf_random_disable(char attribute((unused)) **argv) {
302   if(disorder_random_disable(getclient())) exit(EXIT_FAILURE);
303 }
304
305 static void cf_random_enable(char attribute((unused)) **argv) {
306   if(disorder_random_enable(getclient())) exit(EXIT_FAILURE);
307 }
308
309 static void cf_stats(char attribute((unused)) **argv) {
310   char **vec;
311   int nvec;
312
313   if(disorder_stats(getclient(), &vec, &nvec)) exit(EXIT_FAILURE);
314   for(int n = 0; n < nvec; ++n)
315     xprintf("%s\n", nullcheck(utf82mb(vec[n])));
316   free_strings(nvec, vec);
317 }
318
319 static void cf_get_volume(char attribute((unused)) **argv) {
320   int l, r;
321
322   if(disorder_get_volume(getclient(), &l, &r)) exit(EXIT_FAILURE);
323   xprintf("%d %d\n", l, r);
324 }
325
326 static void cf_set_volume(char **argv) {
327   if(disorder_set_volume(getclient(), atoi(argv[0]), atoi(argv[1]))) exit(EXIT_FAILURE);
328 }
329
330 static void cf_log(char attribute((unused)) **argv) {
331   if(disorder_log(getclient(), sink_stdio("stdout", stdout))) exit(EXIT_FAILURE);
332 }
333
334 static void cf_move(char **argv) {
335   long n;
336   int e;
337   
338   if((e = xstrtol(&n, argv[1], 0, 10)))
339     disorder_fatal(e, "cannot convert '%s'", argv[1]);
340   if(n > INT_MAX || n < INT_MIN)
341     disorder_fatal(e, "%ld out of range", n);
342   if(disorder_move(getclient(), argv[0], (int)n)) exit(EXIT_FAILURE);
343 }
344
345 static void cf_part(char **argv) {
346   char *s;
347
348   if(disorder_part(getclient(), argv[0], argv[1], argv[2], &s)) exit(EXIT_FAILURE);
349   xprintf("%s\n", nullcheck(utf82mb_f(s)));
350 }
351
352 static int isarg_filename(const char *s) {
353   return s[0] == '/';
354 }
355
356 static void cf_authorize(char **argv) {
357   authorize(getclient(), argv[0], argv[1]);
358 }
359
360 static void cf_resolve(char **argv) {
361   char *track;
362
363   if(disorder_resolve(getclient(), argv[0], &track)) exit(EXIT_FAILURE);
364   xprintf("%s\n", nullcheck(utf82mb_f(track)));
365 }
366
367 static void cf_pause(char attribute((unused)) **argv) {
368   if(disorder_pause(getclient())) exit(EXIT_FAILURE);
369 }
370
371 static void cf_resume(char attribute((unused)) **argv) {
372   if(disorder_resume(getclient())) exit(EXIT_FAILURE);
373 }
374
375 static void cf_tags(char attribute((unused)) **argv) {
376   char **vec;
377
378   if(disorder_tags(getclient(), &vec, 0)) exit(EXIT_FAILURE);
379   while(*vec)
380       xprintf("%s\n", nullcheck(utf82mb(*vec++)));
381 }
382
383 static void cf_users(char attribute((unused)) **argv) {
384   char **vec;
385
386   if(disorder_users(getclient(), &vec, 0)) exit(EXIT_FAILURE);
387   while(*vec)
388     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
389 }
390
391 static void cf_get_global(char **argv) {
392   char *value;
393
394   if(disorder_get_global(getclient(), argv[0], &value)) exit(EXIT_FAILURE);
395   xprintf("%s\n", nullcheck(utf82mb_f(value)));
396 }
397
398 static void cf_set_global(char **argv) {
399   if(disorder_set_global(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
400 }
401
402 static void cf_unset_global(char **argv) {
403   if(disorder_unset_global(getclient(), argv[0])) exit(EXIT_FAILURE);
404 }
405
406 static int isarg_integer(const char *s) {
407   if(!*s) return 0;
408   while(*s) {
409     if(!isdigit((unsigned char)*s))
410       return 0;
411     ++s;
412   }
413   return 1;
414 }
415
416 static void cf_new(char **argv) {
417   char **vec;
418
419   if(disorder_new_tracks(getclient(), argv[0] ? atol(argv[0]) : 0, &vec, 0))
420     exit(EXIT_FAILURE);
421   while(*vec)
422     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
423 }
424
425 static void cf_rtp_address(char attribute((unused)) **argv) {
426   char *address, *port;
427
428   if(disorder_rtp_address(getclient(), &address, &port)) exit(EXIT_FAILURE);
429   xprintf("address: %s\nport: %s\n", address, port);
430 }
431
432 static int isarg_rights(const char *arg) {
433   return strchr(arg, ',') || !parse_rights(arg, 0, 0);
434 }
435
436 static void cf_adduser(char **argv) {
437   if(disorder_adduser(getclient(), argv[0], argv[1], argv[2]))
438     exit(EXIT_FAILURE);
439 }
440
441 static void cf_deluser(char **argv) {
442   if(disorder_deluser(getclient(), argv[0]))
443     exit(EXIT_FAILURE);
444 }
445
446 static void cf_edituser(char **argv) {
447   if(disorder_edituser(getclient(), argv[0], argv[1], argv[2]))
448     exit(EXIT_FAILURE);
449 }
450
451 static void cf_userinfo(char **argv) {
452   char *s;
453
454   if(disorder_userinfo(getclient(), argv[0], argv[1], &s))
455     exit(EXIT_FAILURE);
456   xprintf("%s\n", nullcheck(utf82mb_f(s)));
457 }
458
459 static int isarg_option(const char *arg) {
460   return arg[0] == '-';
461 }
462
463 static int argvlen(char **argv) {
464   char **start = argv;
465   
466   while(*argv)
467     ++argv;
468   return argv - start;
469 }
470
471 static const struct option setup_guest_options[] = {
472   { "help", no_argument, 0, 'h' },
473   { "online-registration", no_argument, 0, 'r' },
474   { "no-online-registration", no_argument, 0, 'R' },
475   { 0, 0, 0, 0 }
476 };
477
478 static void help_setup_guest(void) {
479   xprintf("Usage:\n"
480           "  disorder setup-guest [OPTIONS]\n"
481           "Options:\n"
482           "  --help, -h                Display usage message\n"
483           "  --online-registration     Enable online registration (default)\n"
484           "  --no-online-registration  Disable online registration\n");
485   xfclose(stdout);
486   exit(0);
487 }
488
489 static void cf_setup_guest(char **argv) {
490   int n, online_registration = 1;
491   
492   while((n = getopt_long(argvlen(argv) + 1, argv - 1,
493                          "hrR", setup_guest_options, 0)) >= 0) {
494     switch(n) {
495     case 'h': help_setup_guest();
496     case 'r': online_registration = 1; break;
497     case 'R': online_registration = 0; break;
498     default: disorder_fatal(0, "invalid option");
499     }
500   }
501   if(online_registration && !config->mail_sender)
502     disorder_fatal(0, "you MUST set mail_sender if you want online registration");
503   if(disorder_adduser(getclient(), "guest", "",
504                       online_registration ? "read,register" : "read"))
505     exit(EXIT_FAILURE);
506 }
507
508 struct scheduled_event {
509   time_t when;
510   struct kvp *actiondata;
511   char *id;
512 };
513
514 static int compare_event(const void *av, const void *bv) {
515   struct scheduled_event *a = (void *)av, *b = (void *)bv;
516
517   /* Primary sort key is the trigger time */
518   if(a->when < b->when)
519     return -1;
520   else if(a->when > b->when)
521     return 1;
522   /* For events that go off at the same time just sort by ID */
523   return strcmp(a->id, b->id);
524 }
525
526 static void cf_schedule_list(char attribute((unused)) **argv) {
527   char **ids;
528   int nids, n;
529   struct scheduled_event *events;
530   char tb[128];
531   const char *action, *key, *value, *priority;
532   int prichar;
533
534   /* Get all known events */
535   if(disorder_schedule_list(getclient(), &ids, &nids))
536     exit(EXIT_FAILURE);
537   events = xcalloc(nids, sizeof *events);
538   for(n = 0; n < nids; ++n) {
539     events[n].id = ids[n];
540     if(disorder_schedule_get(getclient(), ids[n], &events[n].actiondata))
541       exit(EXIT_FAILURE);
542     events[n].when = atoll(kvp_get(events[n].actiondata, "when"));
543   }
544   /* Sort by trigger time */
545   qsort(events, nids, sizeof *events, compare_event);
546   /* Display them */
547   for(n = 0; n < nids; ++n) {
548     strftime(tb, sizeof tb, "%Y-%m-%d %H:%M:%S %Z", localtime(&events[n].when));
549     action = kvp_get(events[n].actiondata, "action");
550     priority = kvp_get(events[n].actiondata, "priority");
551     if(!strcmp(priority, "junk"))
552       prichar = 'J';
553     else if(!strcmp(priority, "normal"))
554       prichar = 'N';
555     else
556       prichar = '?';
557     xprintf("%11s %-25s %c %-8s %s",
558             events[n].id, tb, prichar, kvp_get(events[n].actiondata, "who"),
559             action);
560     if(!strcmp(action, "play"))
561       xprintf(" %s",
562               nullcheck(utf82mb(kvp_get(events[n].actiondata, "track"))));
563     else if(!strcmp(action, "set-global")) {
564       key = kvp_get(events[n].actiondata, "key");
565       value = kvp_get(events[n].actiondata, "value");
566       if(value)
567         xprintf(" %s=%s",
568                 nullcheck(utf82mb(key)),
569                 nullcheck(utf82mb(value)));
570       else
571         xprintf(" %s unset",
572                 nullcheck(utf82mb(key)));
573     }
574     xprintf("\n");
575   }
576 }
577
578 static void cf_schedule_del(char **argv) {
579   if(disorder_schedule_del(getclient(), argv[0]))
580     exit(EXIT_FAILURE);
581 }
582
583 static void cf_schedule_play(char **argv) {
584   if(disorder_schedule_add(getclient(),
585                            dateparse(argv[0]),
586                            argv[1],
587                            "play",
588                            argv[2]))
589     exit(EXIT_FAILURE);
590 }
591
592 static void cf_schedule_set_global(char **argv) {
593   if(disorder_schedule_add(getclient(),
594                            dateparse(argv[0]),
595                            argv[1],
596                            "set-global",
597                            argv[2],
598                            argv[3]))
599     exit(EXIT_FAILURE);
600 }
601
602 static void cf_schedule_unset_global(char **argv) {
603   if(disorder_schedule_add(getclient(),
604                            dateparse(argv[0]),
605                            argv[1],
606                            "set-global",
607                            argv[2],
608                            (char *)0))
609     exit(EXIT_FAILURE);
610 }
611
612 static void cf_adopt(char **argv) {
613   if(disorder_adopt(getclient(), argv[0]))
614     exit(EXIT_FAILURE);
615 }
616
617 static void cf_playlists(char attribute((unused)) **argv) {
618   char **vec;
619   int nvec;
620
621   if(disorder_playlists(getclient(), &vec, &nvec))
622     exit(EXIT_FAILURE);
623   for(int n = 0; n < nvec; ++n)
624     xprintf("%s\n", nullcheck(utf82mb(vec[n])));
625   free_strings(nvec, vec);
626 }
627
628 static void cf_playlist_del(char **argv) {
629   if(disorder_playlist_delete(getclient(), argv[0]))
630     exit(EXIT_FAILURE);
631 }
632
633 static void cf_playlist_get(char **argv) {
634   char **vec;
635   int nvec;
636
637   if(disorder_playlist_get(getclient(), argv[0], &vec, &nvec))
638     exit(EXIT_FAILURE);
639   for(int n = 0; n < nvec; ++n)
640     xprintf("%s\n", nullcheck(utf82mb(vec[n])));
641   free_strings(nvec, vec);
642 }
643
644 static void cf_playlist_set(char **argv) {
645   struct vector v[1];
646   FILE *input;
647   const char *tag;
648   char *l;
649
650   if(argv[1]) {
651     // Read track list from file
652     if(!(input = fopen(argv[1], "r")))
653       disorder_fatal(errno, "opening %s", argv[1]);
654     tag = argv[1];
655   } else {
656     // Read track list from standard input
657     input = stdin;
658     tag = "stdin";
659   }
660   vector_init(v);
661   while(!inputline(tag, input, &l, '\n')) {
662     if(!strcmp(l, "."))
663       break;
664     vector_append(v, l);
665   }
666   if(ferror(input))
667     disorder_fatal(errno, "reading %s", tag);
668   if(input != stdin)
669     fclose(input);
670   if(disorder_playlist_lock(getclient(), argv[0])
671      || disorder_playlist_set(getclient(), argv[0], v->vec, v->nvec)
672      || disorder_playlist_unlock(getclient()))
673     exit(EXIT_FAILURE);
674 }
675
676 static const struct command {
677   const char *name;
678   int min, max;
679   void (*fn)(char **);
680   int (*isarg)(const char *);
681   const char *argstr, *desc;
682 } commands[] = {
683   { "adduser",        2, 3, cf_adduser, isarg_rights, "USERNAME PASSWORD [RIGHTS]",
684                       "Create a new user" },
685   { "adopt",          1, 1, cf_adopt, 0, "ID",
686                       "Adopt a randomly picked track" },
687   { "allfiles",       1, 2, cf_allfiles, isarg_regexp, "DIR [~REGEXP]",
688                       "List all files and directories in DIR" },
689   { "authorize",      1, 2, cf_authorize, isarg_rights, "USERNAME [RIGHTS]",
690                       "Authorize user USERNAME to connect" },
691   { "deluser",        1, 1, cf_deluser, 0, "USERNAME",
692                       "Delete user USERNAME" },
693   { "dirs",           1, 2, cf_dirs, isarg_regexp, "DIR [~REGEXP]",
694                       "List directories in DIR" },
695   { "disable",        0, 0, cf_disable, 0, "",
696                       "Disable play" },
697   { "disable-random", 0, 0, cf_random_disable, 0, "",
698                       "Disable random play" },
699   { "edituser",       3, 3, cf_edituser, 0, "USERNAME PROPERTY VALUE",
700                       "Set a property of user USERNAME" },
701   { "enable",         0, 0, cf_enable, 0, "",
702                       "Enable play" },
703   { "enable-random",  0, 0, cf_random_enable, 0, "",
704                       "Enable random play" },
705   { "files",          1, 2, cf_files, isarg_regexp, "DIR [~REGEXP]",
706                       "List files in DIR" },
707   { "get",            2, 2, cf_get, 0, "TRACK NAME",
708                       "Get a preference value" },
709   { "get-global",     1, 1, cf_get_global, 0, "NAME",
710                       "Get a global preference value" },
711   { "get-volume",     0, 0, cf_get_volume, 0, "",
712                       "Get the current volume" },
713   { "length",         1, 1, cf_length, 0, "TRACK",
714                       "Get the length of TRACK in seconds" },
715   { "log",            0, 0, cf_log, 0, "",
716                       "Copy event log to stdout" },
717   { "move",           2, 2, cf_move, 0, "TRACK DELTA",
718                       "Move a track in the queue" },
719   { "new",            0, 1, cf_new, isarg_integer, "[MAX]",
720                       "Get the most recently added MAX tracks" },
721   { "part",           3, 3, cf_part, 0, "TRACK CONTEXT PART",
722                       "Find a track name part" },
723   { "pause",          0, 0, cf_pause, 0, "",
724                       "Pause the currently playing track" },
725   { "play",           1, INT_MAX, cf_play, isarg_filename, "TRACKS...",
726                       "Add TRACKS to the end of the queue" },
727   { "playing",        0, 0, cf_playing, 0, "",
728                       "Report the playing track" },
729   { "playlist-del",   1, 1, cf_playlist_del, 0, "PLAYLIST",
730                       "Delete a playlist" },
731   { "playlist-get",   1, 1, cf_playlist_get, 0, "PLAYLIST",
732                       "Get the contents of a playlist" },
733   { "playlist-set",   1, 2, cf_playlist_set, isarg_filename, "PLAYLIST [PATH]",
734                       "Set the contents of a playlist" },
735   { "playlists",      0, 0, cf_playlists, 0, "",
736                       "List playlists" },
737   { "prefs",          1, 1, cf_prefs, 0, "TRACK",
738                       "Display all the preferences for TRACK" },
739   { "quack",          0, 0, cf_quack, 0, 0, 0 },
740   { "queue",          0, 0, cf_queue, 0, "",
741                       "Display the current queue" },
742   { "random-disable", 0, 0, cf_random_disable, 0, "",
743                       "Disable random play" },
744   { "random-enable",  0, 0, cf_random_enable, 0, "",
745                       "Enable random play" },
746   { "recent",         0, 0, cf_recent, 0, "",
747                       "Display recently played track" },
748   { "reconfigure",    0, 0, cf_reconfigure, 0, "",
749                       "Reconfigure the daemon" },
750   { "remove",         1, 1, cf_remove, 0, "TRACK",
751                       "Remove a track from the queue" },
752   { "rescan",         0, 0, cf_rescan, 0, "",
753                       "Rescan for new tracks" },
754   { "resolve",        1, 1, cf_resolve, 0, "TRACK",
755                       "Resolve alias for TRACK" },
756   { "resume",         0, 0, cf_resume, 0, "",
757                       "Resume after a pause" },
758   { "rtp-address",    0, 0, cf_rtp_address, 0, "",
759                       "Report server's broadcast address" },
760   { "schedule-del",   1, 1, cf_schedule_del, 0, "EVENT",
761                       "Delete a scheduled event" },
762   { "schedule-list",  0, 0, cf_schedule_list, 0, "",
763                       "List scheduled events" },
764   { "schedule-play",  3, 3, cf_schedule_play, 0, "WHEN PRI TRACK",
765                       "Play TRACK later" },
766   { "schedule-set-global", 4, 4, cf_schedule_set_global, 0, "WHEN PRI NAME VAL",
767                       "Set a global preference later" },
768   { "schedule-unset-global", 3, 3, cf_schedule_unset_global, 0, "WHEN PRI NAME",
769                       "Unset a global preference later" },
770   { "scratch",        0, 0, cf_scratch, 0, "",
771                       "Scratch the currently playing track" },
772   { "scratch-id",     1, 1, cf_scratch, 0, "ID",
773                       "Scratch the currently playing track" },
774   { "search",         1, 1, cf_search, 0, "WORDS",
775                       "Display tracks matching all the words" },
776   { "set",            3, 3, cf_set, 0, "TRACK NAME VALUE",
777                       "Set a preference value" },
778   { "set-global",     2, 2, cf_set_global, 0, "NAME VALUE",
779                       "Set a global preference value" },
780   { "set-volume",     2, 2, cf_set_volume, 0, "LEFT RIGHT",
781                       "Set the volume" },
782   { "setup-guest",    0, INT_MAX, cf_setup_guest, isarg_option, "[OPTIONS]",
783                       "Create the guest login" },
784   { "shutdown",       0, 0, cf_shutdown, 0, "",
785                       "Shut down the daemon" },
786   { "stats",          0, 0, cf_stats, 0, "",
787                       "Display server statistics" },
788   { "tags",           0, 0, cf_tags, 0, "",
789                       "List known tags" },
790   { "unset",          2, 2, cf_unset, 0, "TRACK NAME",
791                       "Unset a preference" },
792   { "unset-global",   1, 1, cf_unset_global, 0, "NAME",
793                       "Unset a global preference" },
794   { "userinfo",       2, 2, cf_userinfo, 0, "USERNAME PROPERTY",
795                       "Get a property of a user" },
796   { "users",          0, 0, cf_users, 0, "",
797                       "List all users" },
798   { "version",        0, 0, cf_version, 0, "",
799                       "Display the server version" },
800 };
801
802 static void help_commands(void) {
803   unsigned n, max = 0, l;
804
805   xprintf("Command summary:\n");
806   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
807     if(!commands[n].desc) continue;
808     l = strlen(commands[n].name);
809     if(*commands[n].argstr)
810       l += strlen(commands[n].argstr) + 1;
811     if(l > max)
812       max = l;
813   }
814   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
815     if(!commands[n].desc) continue;
816     l = strlen(commands[n].name);
817     if(*commands[n].argstr)
818       l += strlen(commands[n].argstr) + 1;
819     xprintf("  %s%s%s%*s  %s\n", commands[n].name,
820             *commands[n].argstr ? " " : "",
821             commands[n].argstr,
822             max - l, "",
823             commands[n].desc);
824   }
825   xfclose(stdout);
826   exit(0);
827 }
828
829 static void wait_for_root(void) {
830   const char *password;
831
832   while(!trackdb_readable()) {
833     disorder_info("waiting for trackdb...");
834     sleep(1);
835   }
836   trackdb_init(TRACKDB_NO_RECOVER|TRACKDB_NO_UPGRADE);
837   for(;;) {
838     trackdb_open(TRACKDB_READ_ONLY);
839     password = trackdb_get_password("root");
840     trackdb_close();
841     if(password)
842       break;
843     disorder_info("waiting for root user to be created...");
844     sleep(1);
845   }
846   trackdb_deinit(NULL);
847 }
848
849 int main(int argc, char **argv) {
850   int n, i, j, local = 0, wfr = 0;
851   int status = 0;
852   struct vector args;
853   const char *user = 0, *password = 0;
854
855   mem_init();
856   /* garbage-collect PCRE's memory */
857   pcre_malloc = xmalloc;
858   pcre_free = xfree;
859   if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale");
860   if(!setlocale(LC_TIME, "")) disorder_fatal(errno, "error calling setlocale");
861   while((n = getopt_long(argc, argv, "+hVc:dHlNu:p:W", options, 0)) >= 0) {
862     switch(n) {
863     case 'h': help();
864     case 'H': help_commands();
865     case 'V': version("disorder");
866     case 'c': configfile = optarg; break;
867     case 'd': debugging = 1; break;
868     case 'l': local = 1; break;
869     case 'N': config_per_user = 0; break;
870     case 'u': user = optarg; break;
871     case 'p': password = optarg; break;
872     case 'W': wfr = 1; break;
873     default: disorder_fatal(0, "invalid option");
874     }
875   }
876   if(config_read(0, NULL)) disorder_fatal(0, "cannot read configuration");
877   if(user) {
878     xfree(config->username);
879     config->username = xstrdup(user);
880     config->password = 0;
881   }
882   if(password) {
883     xfree(config->password);
884     config->password = xstrdup(password);
885   }
886   if(local)
887     config->connect.af = -1;
888   if(wfr)
889     wait_for_root();
890   n = optind;
891   optind = 1;                           /* for subsequent getopt calls */
892   /* gcrypt initialization */
893   if(!gcry_check_version(NULL))
894     disorder_fatal(0, "gcry_check_version failed");
895   gcry_control(GCRYCTL_INIT_SECMEM, 0);
896   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
897   /* accumulate command args */
898   while(n < argc) {
899     if((i = TABLE_FIND(commands, name, argv[n])) < 0)
900       disorder_fatal(0, "unknown command '%s'", argv[n]);
901     if(n + commands[i].min >= argc)
902       disorder_fatal(0, "missing arguments to '%s'", argv[n]);
903     vector_init(&args);
904     /* Include the command name in the args, but at element -1, for
905      * the benefit of subcommand getopt calls */
906     vector_append(&args, xstrdup(argv[n]));
907     n++;
908     for(j = 0; j < commands[i].min; ++j)
909       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
910     for(; j < commands[i].max
911           && n + j < argc
912           && commands[i].isarg(argv[n + j]); ++j)
913       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
914     vector_terminate(&args);
915     commands[i].fn(args.vec + 1);
916     vector_clear(&args);
917     n += j;
918   }
919   if(client && disorder_close(client)) exit(EXIT_FAILURE);
920   if(fclose(stdout) < 0) disorder_fatal(errno, "error closing stdout");
921   config_free(config);
922   xfree(client);
923   return status;
924 }
925
926 /*
927 Local Variables:
928 c-basic-offset:2
929 comment-column:40
930 End:
931 */