1fe7cc72758346b30516d237b9a987aae5ecbfbd
[project/uci.git] / cli.c
1 /*
2 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2
6 * as published by the Free Software Foundation
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
13 #include <strings.h>
14 #include <stdlib.h>
15 #include "uci.h"
16
17 static struct uci_context *ctx;
18 static char *buf = NULL;
19 static int buflen = 256;
20
21 static void uci_usage(int argc, char **argv)
22 {
23 fprintf(stderr,
24 "Usage: %s [<options>] <command> [<arguments>]\n\n"
25 "Commands:\n"
26 "\tshow [<config>[.<section>[.<option>]]]\n"
27 "\texport [<config>]\n"
28 "\n",
29 argv[0]
30 );
31 exit(255);
32 }
33
34 static void uci_show_section(struct uci_section *p)
35 {
36 struct uci_option *o;
37 const char *cname, *sname;
38
39 cname = p->package->name;
40 sname = p->name;
41 printf("%s.%s=%s\n", cname, sname, p->type);
42 uci_foreach_entry(option, &p->options, o) {
43 printf("%s.%s.%s=%s\n", cname, sname, o->name, o->value);
44 }
45 }
46
47 static int uci_show(int argc, char **argv)
48 {
49 char *section = (argc > 2 ? argv[2] : NULL);
50 struct uci_package *package;
51 struct uci_section *s;
52 char **configs;
53 char **p;
54
55 configs = uci_list_configs();
56 if (!configs)
57 return 0;
58
59 for (p = configs; *p; p++) {
60 if ((argc < 2) || !strcmp(argv[1], *p)) {
61 if (uci_load(ctx, *p, &package) != UCI_OK) {
62 uci_perror(ctx, "uci_load");
63 return 255;
64 }
65 uci_foreach_entry(section, &package->sections, s) {
66 if (!section || !strcmp(s->name, section))
67 uci_show_section(s);
68 }
69 uci_unload(ctx, *p);
70 }
71 }
72
73 return 0;
74 }
75
76 static int uci_do_export(int argc, char **argv)
77 {
78 char **configs = uci_list_configs();
79 char **p;
80
81 if (!configs)
82 return 0;
83
84 for (p = configs; *p; p++) {
85 if ((argc < 2) || !strcmp(argv[1], *p)) {
86 struct uci_package *package = NULL;
87 int ret;
88
89 ret = uci_load(ctx, *p, &package);
90 if (ret)
91 continue;
92 uci_export(ctx, stdout, package);
93 uci_unload(ctx, *p);
94 }
95 }
96 return 0;
97 }
98
99 static int uci_cmd(int argc, char **argv)
100 {
101 if (!strcasecmp(argv[0], "show"))
102 return uci_show(argc, argv);
103 if (!strcasecmp(argv[0], "export"))
104 return uci_do_export(argc, argv);
105 return 255;
106 }
107
108 int main(int argc, char **argv)
109 {
110 int ret;
111
112 ctx = uci_alloc();
113 if (argc < 2)
114 uci_usage(argc, argv);
115 ret = uci_cmd(argc - 1, argv + 1);
116 if (ret == 255)
117 uci_usage(argc, argv);
118 uci_free(ctx);
119
120 return ret;
121 }