/*
 * Copyright (c) 2012-2017, Robin Hahling
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of the author nor the names of its contributors may be
 *   used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * dotfile.c
 *
 * Handle configuration file
 */

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <limits.h>

#include "dotfile.h"

#ifdef NLS_ENABLED
#include <libintl.h>
#endif

/* static functions declaration */
static int get_boolean_value(const char *val);
static int set_conf(const char *key, const char *val);

/*
 * Get boolean value from a string like ("yes"/"true" or "no"/"false")
 * Return 1 if "yes"/"true", 0 if "no"/"false", or -1 if not a boolean.
 * Note that this function is NOT case sensitive.
 * @val: value to check
*/
static int
get_boolean_value(const char *val)
{
	if ((strcasecmp(val, "yes") == 0) || (strcasecmp(val, "true") == 0))
		return 1;
	else if ((strcasecmp(val, "no") == 0) || (strcasecmp(val, "false") == 0))
		return 0;
	else
		return -1;
}

/*
 * Finds the configuration file and returns its path.
 * NULL is returned when no configuration file is found.
 * Configuration file follows XDG Base Directory Specification
 * http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
 */
char *
config_file(void)
{
	char *xdg_home, *home;
	char conf[PATH_MAX];
	int ret;

	xdg_home = getenv("XDG_CONFIG_HOME");
	if (xdg_home && *xdg_home) {
		ret = snprintf(conf, sizeof(conf), "%s/dfc/dfcrc", xdg_home);
		if (ret < 0)
			return NULL;
		if ((size_t)ret >= sizeof(conf))
			goto trunc_err;
		if (access(conf, F_OK) == 0)
			return strdup(conf);
	}

	home = getenv("HOME");
	if (home && *home) {
		ret = snprintf(conf, sizeof(conf), "%s/.config/dfc/dfcrc", home);
		if (ret < 0)
			return NULL;
		if ((size_t)ret >= sizeof(conf))
			goto trunc_err;
		if (access(conf, F_OK) == 0)
			return strdup(conf);

		ret = snprintf(conf, sizeof(conf), "%s/.dfcrc", home);
		if (ret < 0)
			return NULL;
		if ((size_t)ret >= sizeof(conf))
			goto trunc_err;
		if (access(conf, F_OK) == 0)
			return strdup(conf);
	}
	return NULL;

trunc_err:
	(void)fprintf(
		stderr,
		_("Config file path is longer than %lu and was truncated. "
		  "Please, open a bug report.\n"),
		sizeof(conf)
	);
	return NULL;
}

/*
 * Parse the configuration file and update options
 * return -1 in case of error, otherwise, 0 is returned
 * @conf: path to the configuration file
 */
int
update_conf(const char *conf)
{
	FILE *fd;
	char line[255];
	char *key, *val;
	int ret = 0;

	if ((fd = fopen(conf, "r")) == NULL) {
		(void)fprintf(stderr, "Cannot read file %s", conf);
		perror(" ");
		return -1;
	}

	while ((fgets(line, (int)sizeof(line), fd)) != NULL) {

		/* skip empty lines and lines beginning with # */
		if (!strlen(strtrim(line)) || line[0] == '#')
			continue;

		key = strtok(line, "=");
		val = strtok(NULL, "");

		key = strtrim(key);
		if ((val = strtrim(val)) == NULL) {
			(void)fprintf(stderr, _("Error: no value for %s in "
				"configuration file\n"), key);
			if (fclose(fd) == EOF)
				perror("Could not close configuration file ");
			return -1;
		}

		ret += set_conf(key, val);
	}

	if (fclose(fd) == EOF)
		perror("Could not close configuration file ");

	if (ret < 0)
		return -1;

	return ret;
}

/*
 * Set configuration values taken from the configuration file
 * Return 0 if no error occurred, -1 otherwise.
 * @key: key in configuration file
 * @val: value corresponding to the key
 */
static int
set_conf(const char *key, const char *val)
{
	int tmp;
	int ret = 0;

	if (strcmp(key, "bold_font") == 0) {
		if ((tmp = get_boolean_value(val)) == -1)
			goto unknown_boolean_value;
		else if (tmp == 1)
			cnf.font_type = BOLD_FONT;
		else if (tmp == 0)
			cnf.font_type = REGULAR_FONT;
	}
	else if (strcmp(key, "color_header") == 0) {
		if ((tmp = colortoint(val)) == -1)
			goto unknown_color_value;
		else
			cnf.chead = tmp;
	} else if (strcmp(key, "color_low") == 0) {
		if ((tmp = colortoint(val)) == -1)
			goto unknown_color_value;
		else
			cnf.clow = tmp;
	} else if (strcmp(key, "color_medium") == 0) {
		if ((tmp = colortoint(val)) == -1)
			goto unknown_color_value;
		else
			cnf.cmedium = tmp;
	} else if (strcmp(key, "color_high") == 0) {
		if ((tmp = colortoint(val)) == -1)
			goto unknown_color_value;
		else
			cnf.chigh = tmp;
	} else if (strcmp(key, "graph_medium") == 0) {
		ret = -1;
		/* reset errno value for strtol (see strtol(3)) */
		errno = 0;
		tmp = (int)strtol(val, (char **) NULL, 10);
		if (errno)
			(void)fprintf(stderr, _("Value conversion failed"
				" for graph_medium: %s. What were you "
				"expecting with such a thing anyway?\n"),
				val);
		else if (tmp < 0)
			(void)fprintf(stderr, _("Medium value cannot be"
				" set below 0: %s\n"), val);
		else if (tmp > 100)
			(void)fprintf(stderr, _("Medium value cannot be"
				" set above 100: %s\n"), val);
		else {
			ret = 0;
			cnf.gmedium = tmp;
		}
	} else if (strcmp(key, "graph_high") == 0) {
		ret = -1;
		/* reset errno value for strtol (see strtol(3)) */
		errno = 0;
		tmp = (int)strtol(val, (char **) NULL, 10);
		if (errno)
			(void)fprintf(stderr, _("Value conversion failed"
				" for graph_medium: %s. What were you "
				"expecting with such a thing anyway?\n"),
				val);
		else if (tmp < 0)
			(void)fprintf(stderr, _("High value cannot be"
				" set below 0: %s\n"), val);
		else if (tmp > 100)
			(void)fprintf(stderr, _("High value cannot be"
				" set above 100: %s\n"), val);
		else {
			ret = 0;
			cnf.ghigh = tmp;
		}
	} else if (strcmp(key, "graph_symbol") == 0) {
		if (strlen(val) == 1)
			cnf.gsymbol = val[0];
		else {
			(void)fprintf(stderr, _("Wrong symbol value: "
					"%s\n"), val);
			ret = -1;
		}
	} else if (strcmp(key, "html_color_header_bg") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hcheadbg, sizeof(cnf.hcheadbg), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_header_fg") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hcheadfg, sizeof(cnf.hcheadfg), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_cell_bg") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hccellbg, sizeof(cnf.hccellbg), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_cell_fg") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hccellfg, sizeof(cnf.hccellfg), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_hover_bg") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hchoverbg, sizeof(cnf.hchoverbg), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_hover_fg") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hchoverfg, sizeof(cnf.hchoverfg), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_low") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hclow, sizeof(cnf.hclow), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_medium") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hcmedium, sizeof(cnf.hcmedium), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "html_color_high") == 0) {
		if (chk_html_colorcode(val) != 0)
			goto non_valid_html_color;
		if (snprintf(cnf.hchigh, sizeof(cnf.hchigh), "%s", val) != HEXCOLOR_LEN)
			goto assignment_failed;
	} else if (strcmp(key, "csv_separator") == 0) {
		if (strlen(val) == 1)
			cnf.csvsep = val[0];
		else {
			(void)fprintf(stderr, _("Wrong csv separator: "
					"%s\n"), val);
			ret = -1;
		}
	} else {
		(void)fprintf(stderr, _("Error: unknown option in configuration"
				" file: %s\n"), key);
		ret = -1;
	}

	return ret;

unknown_boolean_value:
	(void)fprintf(stderr, _("Unknown boolean value for '%s': %s\n"), key, val);
	return -1;

unknown_color_value:
	(void)fprintf(stderr, _("Unknown color value for '%s': %s\n"), key, val);
	return -1;

non_valid_html_color:
	(void)fprintf(stderr, _("Not a valid HTML color for '%s': %s\n"), key, val);
	return -1;

assignment_failed:
	(void)fprintf(stderr, _("Cannot assign value for '%s': %s\n"), key, val);
	return -1;
}

/**
 * Init a conf structure with default valuues.
 * @cnf: structure to be initiated
 */
void
init_conf(struct conf *config)
{
	config->chead	= BLUE;
	config->clow	= GREEN;
	config->cmedium	= YELLOW;
	config->chigh	= RED;

	config->gmedium	= 50;
	config->ghigh	= 75;

	config->gsymbol	= '=';

	(void)snprintf(config->hcheadbg, sizeof(config->hcheadbg), "%s", "970000");
	(void)snprintf(config->hcheadfg, sizeof(config->hcheadfg), "%s", "FFFFFF");
	(void)snprintf(config->hccellbg, sizeof(config->hccellbg), "%s", "E9E9E9");
	(void)snprintf(config->hccellfg, sizeof(config->hccellfg), "%s", "000000");
	(void)snprintf(config->hchoverbg, sizeof(config->hchoverbg), "%s", "FFFFFF");
	(void)snprintf(config->hchoverfg, sizeof(config->hchoverfg), "%s", "000000");
	(void)snprintf(config->hclow, sizeof(config->hclow), "%s", "348017");
	(void)snprintf(config->hcmedium, sizeof(config->hcmedium), "%s", "FDD017");
	(void)snprintf(config->hchigh, sizeof(config->hchigh), "%s", "F62217");

	config->csvsep = ',';
}
