+static void
+uci_lua_add_change(lua_State *L, struct uci_element *e)
+{
+ struct uci_history *h;
+ const char *name;
+
+ h = uci_to_history(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 ? h->e.name : ".type");
+ if (h->value)
+ lua_pushstring(L, h->value);
+ else
+ lua_pushstring(L, "");
+ lua_setfield(L, -2, name);
+ lua_pop(L, 1);
+}
+
+static void
+uci_lua_changes_pkg(lua_State *L, const char *package)
+{
+ struct uci_package *p = NULL;
+ struct uci_element *e;
+ bool autoload = false;
+
+ p = find_package(L, package, AUTOLOAD_OFF);
+ if (!p) {
+ autoload = true;
+ p = find_package(L, package, AUTOLOAD_FORCE);
+ if (!p)
+ return;
+ }
+
+ if (uci_list_empty(&p->history) && uci_list_empty(&p->saved_history))
+ goto done;
+
+ lua_newtable(L);
+ uci_foreach_element(&p->saved_history, e) {
+ uci_lua_add_change(L, e);
+ }
+ uci_foreach_element(&p->history, 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)
+{
+ const char *package = NULL;
+ char **config = NULL;
+ int nargs;
+ int i;
+
+ nargs = lua_gettop(L);
+ switch(nargs) {
+ case 1:
+ package = luaL_checkstring(L, 1);
+ case 0:
+ break;
+ default:
+ luaL_error(L, "invalid argument count");
+ }
+
+ lua_newtable(L);
+ if (package) {
+ uci_lua_changes_pkg(L, package);
+ } else {
+ if (uci_list_configs(ctx, &config) != 0)
+ goto done;
+
+ for(i = 0; config[i] != NULL; i++) {
+ uci_lua_changes_pkg(L, config[i]);
+ }
+ }
+
+done:
+ return 1;
+}
+