2 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
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
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.
17 static struct uci_context *ctx;
18 static char *buf = NULL;
19 static int buflen = 256;
21 static void uci_usage(int argc, char **argv)
24 "Usage: %s [<options>] <command> [<arguments>]\n\n"
26 "\tshow [<config>[.<section>[.<option>]]]\n"
27 "\texport [<config>]\n"
34 static char *uci_escape(char *str)
43 p = strchr(str, '\'');
50 if (p + 3 - str >= buflen) {
52 buf = realloc(buf, buflen);
54 fprintf(stderr, "Out of memory\n");
58 memcpy(&buf[pos], s, len);
61 strcpy(&buf[pos], "'\\''");
64 } while ((p = strchr(s, '\'')));
69 static void uci_show_section(struct uci_section *p)
72 const char *cname, *sname;
74 cname = p->config->name;
76 printf("%s.%s=%s\n", cname, sname, p->type);
77 uci_foreach_entry(option, &p->options, o) {
78 printf("%s.%s.%s=%s\n", cname, sname, o->name, o->value);
82 static void uci_export_section(struct uci_section *p)
87 printf("config '%s'", uci_escape(p->type));
88 printf(" '%s'\n", uci_escape(p->name));
89 uci_foreach_entry(option, &p->options, o) {
90 printf("\toption '%s'", uci_escape(o->name));
91 printf(" '%s'\n", uci_escape(o->value));
95 static void foreach_section(const char *name, void (*callback)(struct uci_section *))
97 struct uci_config *cfg;
98 struct uci_section *p;
100 if (uci_load(ctx, name, &cfg) != UCI_OK) {
101 uci_perror(ctx, "uci_load");
105 uci_list_empty(&cfg->sections);
106 uci_foreach_entry(section, &cfg->sections, p) {
109 uci_unload(ctx, name);
112 static int uci_show(int argc, char **argv)
114 char **configs = uci_list_configs();
120 for (p = configs; *p; p++) {
121 fprintf(stderr, "# config: %s\n", *p);
122 foreach_section(*p, uci_show_section);
128 static int uci_export(int argc, char **argv)
130 char **configs = uci_list_configs();
136 for (p = configs; *p; p++) {
137 foreach_section(*p, uci_export_section);
142 static int uci_cmd(int argc, char **argv)
144 if (!strcasecmp(argv[0], "show"))
145 return uci_show(argc, argv);
146 if (!strcasecmp(argv[0], "export"))
147 return uci_export(argc, argv);
151 int main(int argc, char **argv)
157 uci_usage(argc, argv);
158 ret = uci_cmd(argc - 1, argv + 1);
160 uci_usage(argc, argv);