+static void save_config(void) {
+ FILE *fp = NULL, *tmpfp = NULL;
+ char *homedir, *tempfile, *newfile;
+ size_t len;
+ int continuous_mode_seen = 0;
+ int default_browser_seen = 0;
+ int other_browser_cmd_seen = 0;
+ struct swb_config_line line;
+
+ /* If CONFIGFILE_DIR doesn't exist already, try to create it */
+ if (!(homedir = getenv("HOME")))
+ homedir = DEFAULT_HOMEDIR;
+ len = strlen(homedir) + strlen(CONFIGFILE_DIR) + 1;
+ if (!(newfile = calloc(len, sizeof(char))))
+ return;
+ snprintf(newfile, len, "%s%s", homedir, CONFIGFILE_DIR);
+ if (access(newfile, F_OK) == -1 && errno == ENOENT) {
+ mkdir(newfile, 0750);
+ }
+ free(newfile);
+
+ /* Put together the path to the new config file and the tempfile */
+ len = strlen(homedir) + strlen(CONFIGFILE_LOC) + 1;
+ if (!(newfile = calloc(len, sizeof(char))))
+ return;
+ /* 4 = strlen(".tmp") */
+ if (!(tempfile = calloc(len+4, sizeof(char)))) {
+ free(newfile);
+ return;
+ }
+ snprintf(newfile, len, "%s%s", homedir, CONFIGFILE_LOC);
+ snprintf(tempfile, len+4, "%s%s", newfile, ".tmp");
+
+ /* Open the temporary file for writing */
+ if (!(tmpfp = fopen(tempfile, "w")))
+ /* TODO: report the error somehow? */
+ goto out;
+
+ /* Open the old config file, if it exists */
+ if ((fp = open_config_file()) && parse_config_file_begin()) {
+ /* Copy the old config file over to the new one line by line,
+ replacing old config values with new ones
+ TODO: should we handle errors differently than EOF? */
+ while (!parse_config_file_line(fp, &line)) {
+ if (line.parsed) {
+ /* Is a config line, print the new value here */
+ if (!strcmp(line.key, "continuous_mode")) {
+ if (!continuous_mode_seen) {
+ fprintf(tmpfp, "%s = %d\n",
+ line.key,
+ get_continuous_mode());
+ continuous_mode_seen = 1;
+ }
+ } else if (!strcmp(line.key,
+ "default_browser")) {
+ if (!default_browser_seen) {
+ fprintf(tmpfp, "%s = \"%s\"\n",
+ line.key,
+ get_default_browser());
+ default_browser_seen = 1;
+ }
+ } else if (!strcmp(line.key,
+ "other_browser_cmd")) {
+ if (!other_browser_cmd_seen &&
+ strlen(get_other_browser_cmd())>0) {
+ fprintf(tmpfp, "%s = \"%s\"\n",
+ line.key,
+ get_other_browser_cmd());
+ other_browser_cmd_seen = 1;
+ }
+ }
+ } else {
+ /* Just copy the old line over */
+ fprintf(tmpfp, "%s\n", line.key);
+ }
+ free(line.key);
+ free(line.value);
+ }
+ parse_config_file_end();
+ }