+int uci_save(struct uci_context *ctx, struct uci_package *p)
+{
+ FILE *f = NULL;
+ char *filename = NULL;
+ struct uci_element *e, *tmp;
+
+ UCI_HANDLE_ERR(ctx);
+ UCI_ASSERT(ctx, p != NULL);
+
+ /*
+ * if the config file was outside of the /etc/config path,
+ * don't save the history to a file, update the real file
+ * directly.
+ * does not modify the uci_package pointer
+ */
+ if (!p->confdir)
+ return uci_commit(ctx, &p);
+
+ if (uci_list_empty(&p->history))
+ return 0;
+
+ if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
+ UCI_THROW(ctx, UCI_ERR_MEM);
+
+ ctx->errno = 0;
+ UCI_TRAP_SAVE(ctx, done);
+ f = uci_open_stream(ctx, filename, SEEK_END, true, true);
+ UCI_TRAP_RESTORE(ctx);
+
+ uci_foreach_element_safe(&p->history, tmp, e) {
+ struct uci_history *h = uci_to_history(e);
+
+ if (h->cmd == UCI_CMD_REMOVE)
+ fprintf(f, "-");
+
+ fprintf(f, "%s.%s", p->e.name, h->section);
+ if (e->name)
+ fprintf(f, ".%s", e->name);
+
+ if (h->cmd == UCI_CMD_REMOVE)
+ fprintf(f, "\n");
+ else
+ fprintf(f, "=%s\n", h->value);
+ uci_free_history(h);
+ }
+
+done:
+ uci_close_stream(f);
+ if (filename)
+ free(filename);
+ if (ctx->errno)
+ UCI_THROW(ctx, ctx->errno);
+
+ return 0;
+}
+
+int uci_commit(struct uci_context *ctx, struct uci_package **package)
+{
+ struct uci_package *p;
+ FILE *f = NULL;
+ char *name = NULL;
+ char *path = NULL;
+
+ UCI_HANDLE_ERR(ctx);
+ UCI_ASSERT(ctx, package != NULL);
+ p = *package;
+
+ UCI_ASSERT(ctx, p != NULL);
+ UCI_ASSERT(ctx, p->path != NULL);
+
+ /* open the config file for writing now, so that it is locked */
+ f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
+
+ /* flush unsaved changes and reload from history file */
+ UCI_TRAP_SAVE(ctx, done);
+ if (p->confdir) {
+ name = uci_strdup(ctx, p->e.name);
+ path = uci_strdup(ctx, p->path);
+ if (!uci_list_empty(&p->history))
+ UCI_INTERNAL(uci_save, ctx, p);
+ uci_free_package(&p);
+ uci_file_cleanup(ctx);
+ UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
+
+ p->path = path;
+ p->confdir = true;
+ *package = p;
+
+ /* freed together with the uci_package */
+ path = NULL;
+
+ /* check for updated history, just in case */
+ uci_load_history(ctx, p, true);
+ }
+
+ rewind(f);
+ ftruncate(fileno(f), 0);
+
+ uci_export(ctx, f, p, false);
+ UCI_TRAP_RESTORE(ctx);
+
+done:
+ if (name)
+ free(name);
+ if (path)
+ free(path);
+ uci_close_stream(f);
+ if (ctx->errno)
+ UCI_THROW(ctx, ctx->errno);
+
+ return 0;
+}
+
+