+static void
+uci_lua_add_change(lua_State *L, struct uci_element *e)
+{
+ struct uci_delta *h;
+ const char *name;
+ const char *value;
+
+ h = uci_to_delta(e);
+ if (!h->section)
+ return;
+
+ lua_getfield(L, -1, h->section);
+ if (lua_isnil(L, -1)) {
+ lua_pop(L, 1);
+ lua_newtable(L);
+ lua_pushvalue(L, -1); /* copy for setfield */
+ lua_setfield(L, -3, h->section);
+ }
+
+ name = h->e.name;
+ value = h->value ? h->value : "";
+
+ if (name) {
+ lua_getfield(L, -1, name);
+
+ /* there seems to be no value yet so simply push it as string */
+ if (lua_isnil(L, -1)) {
+ lua_pushstring(L, value);
+ lua_setfield(L, -3, name);
+
+ /* there is already a value, so this change is a list_add,
+ * coerce string into one-element array and append new value */
+ } else if (lua_isstring(L, -1)) {
+ lua_newtable(L);
+ lua_pushvalue(L, -2);
+ lua_rawseti(L, -2, 1);
+ lua_pushstring(L, value);
+ lua_rawseti(L, -2, 2);
+ lua_setfield(L, -3, name);
+
+ /* a table is on the top of the stack so this is a subsequent,
+ * list_add, append this value to table */
+ } else if (lua_istable(L, -1)) {
+ lua_pushstring(L, value);
+ lua_rawseti(L, -2, lua_objlen(L, -2) + 1);
+ }
+
+ lua_pop(L, 1);
+ } else {
+ lua_pushstring(L, value);
+ lua_setfield(L, -2, ".type");
+ }
+
+ lua_pop(L, 1);
+}
+
+static void
+uci_lua_changes_pkg(lua_State *L, struct uci_context *ctx, const char *package)
+{
+ struct uci_package *p = NULL;
+ struct uci_element *e;
+ bool autoload = false;
+
+ p = find_package(L, ctx, package, false);
+ if (!p) {
+ autoload = true;
+ p = find_package(L, ctx, package, true);
+ if (!p)
+ return;
+ }
+
+ if (uci_list_empty(&p->delta) && uci_list_empty(&p->saved_delta))
+ goto done;
+
+ lua_newtable(L);
+ uci_foreach_element(&p->saved_delta, e) {
+ uci_lua_add_change(L, e);
+ }
+ uci_foreach_element(&p->delta, e) {
+ uci_lua_add_change(L, e);
+ }
+ lua_setfield(L, -2, p->e.name);
+
+done:
+ if (autoload)
+ uci_unload(ctx, p);
+}
+
+static int
+uci_lua_changes(lua_State *L)
+{
+ struct uci_context *ctx;
+ const char *package = NULL;
+ char **config = NULL;
+ int nargs;
+ int i, offset = 0;
+
+ ctx = find_context(L, &offset);
+ nargs = lua_gettop(L);
+ switch(nargs - offset) {
+ case 1:
+ package = luaL_checkstring(L, 1 + offset);
+ case 0:
+ break;
+ default:
+ return luaL_error(L, "invalid argument count");
+ }
+
+ lua_newtable(L);
+ if (package) {
+ uci_lua_changes_pkg(L, ctx, package);
+ } else {
+ if (uci_list_configs(ctx, &config) != 0)
+ goto done;
+
+ for(i = 0; config[i] != NULL; i++) {
+ uci_lua_changes_pkg(L, ctx, config[i]);
+ }
+ }
+
+done:
+ return 1;
+}
+
+static int
+uci_lua_get_confdir(lua_State *L)
+{
+ struct uci_context *ctx = find_context(L, NULL);
+ lua_pushstring(L, ctx->confdir);
+ return 1;
+}
+