#include "conf-update.h"

bool get_boolean(GKeyFile *conffile, const char *key, bool default_value) {
	GError *error = NULL;
	bool value, invalid_value, key_not_found;

	value = (bool) g_key_file_get_boolean(conffile, PROG_NAME, key, &error);
	invalid_value = (bool) g_error_matches(error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);
	key_not_found = (bool) g_error_matches(error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND);
	g_clear_error(&error);
	if (invalid_value || key_not_found) {
		return default_value;
	} else {
		return value;
	}
}

char *get_string(GKeyFile *conffile, const char *key, char *default_value) {
	char * value;

	if (!(value = g_key_file_get_string(conffile, PROG_NAME, key, NULL))) {
		return default_value;
	} else {
		return value;
	}
}

void read_config() {
	extern struct configuration config;
	GKeyFile *conffile;
	
	// set reasonable defaults
	config.check_actions = TRUE;
	
	if (getenv("EDITOR")) {
		config.edit_tool = strdup(getenv("EDITOR"));
	} else {
		fprintf(stderr, "!!! ERROR: environment variable EDITOR not set; edit your /etc/rc.conf\n"
				        "!!! If you are using sudo, make sure it doesn't clean out the env.\n");
		exit(EXIT_FAILURE);
	}
	
	conffile = g_key_file_new();
	if (!g_key_file_load_from_file(conffile, CONFIG_FILE, G_KEY_FILE_NONE, NULL)) {
		fprintf(stderr, "!!! ERROR: Could not load config file %s\n", CONFIG_FILE);
		exit(EXIT_FAILURE);
	} else {
		config.automerge_trivial = get_boolean(conffile, "autoreplace_trivial", TRUE);
		config.automerge_unmodified = get_boolean(conffile, "autoreplace_unmodified", FALSE);
		config.check_actions = get_boolean(conffile, "confirm_actions", TRUE);
		config.diff_tool = get_string(conffile, "diff_tool", strdup("diff -u"));
		config.pager = get_string(conffile, "pager", strdup(""));
		config.merge_tool = get_string(conffile, "merge_tool", strdup("sdiff -s -o"));
	}
	g_key_file_free(conffile);
}
