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("\nconfig '%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 *configname
, const char *section
, void (*callback
)(struct uci_section
*))
97 struct uci_config
*cfg
;
98 struct uci_section
*p
;
100 if (uci_load(ctx
, configname
, &cfg
) != UCI_OK
) {
101 uci_perror(ctx
, "uci_load");
105 uci_list_empty(&cfg
->sections
);
106 uci_foreach_entry(section
, &cfg
->sections
, p
) {
107 if (!section
|| !strcmp(p
->name
, section
))
110 uci_unload(ctx
, configname
);
113 static int uci_show(int argc
, char **argv
)
115 char **configs
= uci_list_configs();
121 for (p
= configs
; *p
; p
++) {
122 if ((argc
< 2) || !strcmp(argv
[1], *p
))
123 foreach_section(*p
, (argc
> 2 ? argv
[2] : NULL
), uci_show_section
);
129 static int uci_export(int argc
, char **argv
)
131 char **configs
= uci_list_configs();
137 for (p
= configs
; *p
; p
++) {
138 if ((argc
< 2) || !strcmp(argv
[1], *p
)) {
139 printf("package '%s'\n", uci_escape(*p
));
140 foreach_section(*p
, NULL
, uci_export_section
);
147 static int uci_cmd(int argc
, char **argv
)
149 if (!strcasecmp(argv
[0], "show"))
150 return uci_show(argc
, argv
);
151 if (!strcasecmp(argv
[0], "export"))
152 return uci_export(argc
, argv
);
156 int main(int argc
, char **argv
)
162 uci_usage(argc
, argv
);
163 ret
= uci_cmd(argc
- 1, argv
+ 1);
165 uci_usage(argc
, argv
);