+ FILE *fw = fopen(tmpname, "w");
+
+ if(!fw) {
+ logger(mesh, MESHLINK_ERROR, "Cannot open temporary file %s: %s", tmpname, strerror(errno));
+ fclose(fr);
+ return false;
+ }
+
+ char buf[4096];
+ char *sep;
+ int found = 0;
+
+ if(value) {
+ fprintf(fw, "%s = %s\n", key, value);
+ found++;
+ }
+
+ while(readline(fr, buf, sizeof(buf))) {
+ if(!*buf || *buf == '#') {
+ goto copy;
+ }
+
+ sep = strchr(buf, ' ');
+
+ if(!sep) {
+ goto copy;
+ }
+
+ *sep = 0;
+
+ if(strcmp(buf, key)) {
+ *sep = ' ';
+ goto copy;
+ }
+
+ // We found the key and the value. We already added it at the top, so ignore this one.
+ if(value && sep[1] == '=' && sep[2] == ' ' && !strcmp(sep + 3, value)) {
+ continue;
+ }
+
+ // We found the key but with a different value, delete it if wanted.
+ found++;
+
+ if((!value || trim) && found > trim) {
+ continue;
+ }
+
+ *sep = ' ';
+
+copy:
+ fprintf(fw, "%s\n", buf);
+ }
+
+ if(ferror(fr)) {
+ error = true;
+ }
+
+ fclose(fr);
+
+ if(ferror(fw)) {
+ error = true;
+ }
+
+ if(fclose(fw)) {
+ error = true;
+ }
+
+ // If any error occured during reading or writing, exit.
+ if(error) {
+ unlink(tmpname);
+ return false;
+ }
+
+ // Try to atomically replace the old config file with the new one.
+#ifdef HAVE_MINGW
+ char bakname[PATH_MAX];
+ snprintf(bakname, sizeof(bakname), "%s.bak", filename);
+
+ if(rename(filename, bakname) || rename(tmpname, filename)) {
+ rename(bakname, filename);
+#else
+
+ if(rename(tmpname, filename)) {
+#endif
+ return false;
+ } else {
+#ifdef HAVE_MINGW
+ unlink(bakname);
+#endif
+ return true;
+ }
+}