/* -*- indent-tabs-mode:t; c-basic-offset:8 -*-
 *
 * Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org>
 * Released under the terms of the GNU GPL v2.0.
 * Copyright (C) 2008 NXP B.V.
 */

#include <sys/stat.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <libgen.h>
#include <errno.h>

#define LKC_DIRECT_LINK
#include "lkc.h"

// NXP
unsigned int dbg_level = 0;

static void conf_warning(const char *fmt, ...)
	__attribute__ ((format (printf, 1, 2)));

static const char *conf_filename;
static int conf_lineno, conf_warnings, conf_unsaved;

const char conf_defname[] = ".defconfig";

static void conf_warning(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	fprintf(stderr, "%s:%d:warning: ", conf_filename, conf_lineno);
	vfprintf(stderr, fmt, ap);
	fprintf(stderr, "\n");
	va_end(ap);
	conf_warnings++;
}

const char *conf_get_configname(void)
{
	char *name = getenv("PRJCONFIG_CONFIG");

	return name ? name : ".config";
}

static char *conf_expand_value(const char *in)
{
	struct symbol *sym;
	const char *src;
	static char res_value[SYMBOL_MAXLENGTH];
	char *dst, name[SYMBOL_MAXLENGTH];

	res_value[0] = 0;
	dst = name;
	while ((src = strchr(in, '$'))) {
		strncat(res_value, in, src - in);
		src++;
		dst = name;
		while (isalnum(*src) || *src == '_')
			*dst++ = *src++;
		*dst = 0;
		sym = sym_lookup(name, 0);
		sym_calc_value(sym);
		strcat(res_value, sym_get_string_value(sym));
		in = src;
	}
	strcat(res_value, in);

	return res_value;
}

char *conf_get_default_confname(void)
{
	struct stat buf;
	static char fullname[PATH_MAX+1];
	char *env, *name;

	name = conf_expand_value(conf_defname);
	env = getenv(SRCTREE);
	if (env) {
		sprintf(fullname, "%s/%s", env, name);
		if (!stat(fullname, &buf))
			return fullname;
	}
	return name;
}

int conf_read_simple(const char *name, int def)
{
	FILE *in = NULL;
	char line[1024];
	char *p, *p2;
	struct symbol *sym;
	int i, def_flags;

	DBG_ENTER("name=%s", name);

	if (name) {
		in = zconf_fopen(name);
	} else {
		struct property *prop;

		name = conf_get_configname();
		in = zconf_fopen(name);
		if (in)
			goto load;
		sym_add_change_count(1);
		if (!sym_defconfig_list)
			return 1;

		for_all_defaults(sym_defconfig_list, prop) {
			if (expr_calc_value(prop->visible.expr) == no ||
			    prop->expr->type != E_SYMBOL)
				continue;
			name = conf_expand_value(prop->expr->left.sym->name);
			in = zconf_fopen(name);
			if (in) {
				printf(_("#\n"
					 "# using defaults found in %s\n"
					 "#\n"), name);
				goto load;
			}
		}
	}
	if (!in) {
		fprintf(stderr, "Cannot open file %s\n", name);
		DBG_LEAVE("name=%s cannot open file!", name);
		return 1;
	}

load:
	conf_filename = name;
	conf_lineno = 0;
	conf_warnings = 0;
	conf_unsaved = 0;

	def_flags = SYMBOL_DEF << def;
	for_all_symbols(i, sym) {
		sym->flags |= SYMBOL_CHANGED;
		sym->flags &= ~(def_flags|SYMBOL_VALID);
		if (sym_is_choice(sym))
			sym->flags |= def_flags;
		switch (sym->type) {
		case S_INT:
		case S_HEX:
		case S_STRING:
			if (sym->def[def].val)
				free(sym->def[def].val);
		default:
			sym->def[def].val = NULL;
			sym->def[def].tri = no;
		}
	}

	while (fgets(line, sizeof(line), in)) {
		conf_lineno++;
		sym = NULL;
		switch (line[0]) {
		case '#':
			if (line[1]!=' ')
				continue;
			if (memcmp(line + 2, "CONFIG_", 7))
				continue;
			p = strchr(line + 9, ' ');
			if (!p)
				continue;
			*p++ = 0;
			if (strncmp(p, "is not set", 10))
				continue;
			if (def == S_DEF_USER) {
			sym = sym_find(line + 9);
			if (!sym) {
				conf_warning("trying to assign nonexistent symbol %s", line + 9);
				break;
				}
			} else {
				sym = sym_lookup(line + 9, 0);
				if (sym->type == S_UNKNOWN)
					sym->type = S_BOOLEAN;
			}
			if (sym->flags & def_flags) {
				conf_warning("trying to reassign symbol %s", sym->name);
				break;
			}
			switch (sym->type) {
			case S_BOOLEAN:
			case S_TRISTATE:
				sym->def[def].tri = no;
				sym->flags |= def_flags;
				DBG_PRINT("clearing sym %s's SYMBOL_NEW flag", sym->name);
				break;
			default:
				;
			}
			break;

		case 'C':
			if (memcmp(line, "CONFIG_", 7)) {
				conf_warning("unexpected data, expecting\n"
					"CONFIG_...=..."
					"  or\n"
					"# CONFIG_... is not set");
				continue;
			}
			p = strchr(line + 7, '=');
			if (!p)
				continue;
			*p++ = 0;
			p2 = strchr(p, '\n');
			if (p2) {
				*p2-- = 0;
				if (*p2 == '\r')
				*p2 = 0;
			}
			if (def == S_DEF_USER) {
			sym = sym_find(line + 7);
			if (!sym) {
				conf_warning("trying to assign nonexistent symbol %s", line + 7);
				break;
				}
			} else {
				sym = sym_lookup(line + 7, 0);
				if (sym->type == S_UNKNOWN)
					sym->type = S_OTHER;
			}
			if (sym->flags & def_flags) {
				conf_warning("trying to reassign symbol %s", sym->name);
				break;
			}
			switch (sym->type) {
			case S_TRISTATE:
				if (p[0] == 'm') {
					sym->def[def].tri = mod;
					sym->flags |= def_flags;
					break;
				}
			case S_BOOLEAN:
				if (p[0] == 'y') {
					sym->def[def].tri = yes;
					sym->flags |= def_flags;
					break;
				}
				if (p[0] == 'n') {
					sym->def[def].tri = no;
					sym->flags |= def_flags;
					break;
				}
				conf_warning("symbol value '%s' invalid for %s", p, sym->name);
				break;
			case S_OTHER:
				if (*p != '"') {
					for (p2 = p; *p2 && !isspace(*p2); p2++)
						;
					sym->type = S_STRING;
					goto done;
				}
			case S_STRING:
				if (*p++ != '"')
					break;
				for (p2 = p; (p2 = strpbrk(p2, "\"\\")); p2++) {
					if (*p2 == '"') {
						*p2 = 0;
						break;
					}
					memmove(p2, p2 + 1, strlen(p2));
				}
				if (!p2) {
					conf_warning("invalid string found");
					continue;
				}
			case S_INT:
			case S_HEX:
			done:
				if (sym_string_valid(sym, p)) {
					sym->def[def].val = strdup(p);
					sym->flags |= def_flags;
				} else {
					conf_warning("symbol value '%s' invalid for %s", p, sym->name);
					continue;
				}
				break;
			default:
				;
			}
			break;
		case '\r':
		case '\n':
			break;
		default:
			conf_warning("unexpected data");
			continue;
		}
		if (sym && sym_is_choice_value(sym)) {
			struct symbol *cs = prop_get_symbol(sym_get_choice_prop(sym));
			switch (sym->def[def].tri) {
			case no:
				break;
			case mod:
				if (cs->def[def].tri == yes) {
					conf_warning("%s creates inconsistent choice state", sym->name);
					cs->flags &= ~def_flags;
				}
				break;
			case yes:
				if (cs->def[def].tri != no) {
					conf_warning("%s creates inconsistent choice state", sym->name);
					cs->flags &= ~def_flags;
				} else
					cs->def[def].val = sym;
				break;
			}
			cs->def[def].tri = E_OR(cs->def[def].tri, sym->def[def].tri);
		}
		// NXP
		if (sym && (sym->flags & SYMBOL_FROZEN)) {
			sym->curr = sym->def[S_DEF_USER];
			sym->flags |= SYMBOL_VALID | SYMBOL_WRITE;
			DBG_PRINT("sym [%s] setting SYMBOL_WRITE (it is frozen)", DBG_SYM_NAME(sym));
			/* Must set visible here, since we don't call sym_calc_visibility
			   from sym_calc_value anymore.
			   We assume here that all options that appear in the input config file
			   are visible.
			   Not sure if this is correct in all circumstances.
			*/
			sym->visible = yes;
		}
	}
	fclose(in);

	if (modules_sym)
		sym_calc_value(modules_sym);
	DBG_LEAVE("name=%s", name);
	return 0;
}

int conf_read(const char *name)
{
	struct symbol *sym;
	struct property *prop;
	struct expr *e;
	int i, flags;

	sym_set_change_count(0);

	DBG_ENTER("name=%s", name);
	if (conf_read_simple(name, S_DEF_USER)) {
		DBG_LEAVE("name=%s", name);
		return 1;
	}

    sym_set_frozen();

	for_all_symbols(i, sym) {
		sym_calc_value(sym);
		if (sym_is_choice(sym) || (sym->flags & SYMBOL_AUTO))
			goto sym_ok;
		if (sym_has_value(sym) && (sym->flags & SYMBOL_WRITE)) {
			/* check that calculated value agrees with saved value */
			switch (sym->type) {
			case S_BOOLEAN:
			case S_TRISTATE:
				if (sym->def[S_DEF_USER].tri != sym_get_tristate_value(sym)) {
					DBG_PRINT("sym %s sym->user.tri != sym_get_tristate_value(sym) => calculated value does not agree with saved value", sym->name);
					break;
    			}
				if (!sym_is_choice(sym))
					goto sym_ok;
			default:
				if (!strcmp(sym->curr.val, sym->def[S_DEF_USER].val))
					goto sym_ok;
				DBG_PRINT("sym %s => calculated value (%s) does not agree with saved value (%s)",
                    sym->name, (char*)sym->curr.val, (char*)sym->def[S_DEF_USER].val);
				break;
			}
		} else if (!sym_has_value(sym) && !(sym->flags & SYMBOL_WRITE))
			/* no previous value and not saved */
			goto sym_ok;
		conf_unsaved++;
		/* maybe print value in verbose mode... */
	sym_ok:
		if (sym_has_value(sym) && !sym_is_choice_value(sym)) {
			if (sym->visible == no)
				sym->flags &= ~SYMBOL_DEF_USER;
			switch (sym->type) {
			case S_STRING:
			case S_INT:
			case S_HEX:
				if (!sym_string_within_range(sym, sym->def[S_DEF_USER].val))
					sym->flags &= ~(SYMBOL_VALID|SYMBOL_DEF_USER);
			default:
				break;
			}
		}
		if (!sym_is_choice(sym))
			continue;
		prop = sym_get_choice_prop(sym);
		flags = sym->flags;
		for (e = prop->expr; e; e = e->left.expr)
			if (e->right.sym->visible != no)
				flags &= e->right.sym->flags;
		sym->flags &= flags | ~SYMBOL_DEF_USER;
	}

	sym_add_change_count(conf_warnings || conf_unsaved);

	DBG_LEAVE("name=%s", name);
	return 0;
}

int conf_write(const char *name)
{
	FILE *out, *out_h;
	struct symbol *sym;
	struct menu *menu;
	const char *basename;
	char dirname[128], tmpname[128], newname[128];
	int type, l;
	const char *str;
	time_t now;

	DBG_ENTER("to file %s", name);
	dirname[0] = 0;
	if (name && name[0]) {
		struct stat st;
		char *slash;

		if (!stat(name, &st) && S_ISDIR(st.st_mode)) {
			strcpy(dirname, name);
			strcat(dirname, "/");
			basename = conf_get_configname();
		} else if ((slash = strrchr(name, '/'))) {
			int size = slash - name + 1;
			memcpy(dirname, name, size);
			dirname[size] = 0;
			if (slash[1])
				basename = slash + 1;
			else
				basename = conf_get_configname();
		} else
			basename = name;
	} else
		basename = conf_get_configname();

	sprintf(newname, "%s.tmpconfig.%d", dirname, (int)getpid());
	DBG_PRINT("Writing to %s\n", newname);
	out = fopen(newname, "w");
	if (!out) {
		fprintf(stderr, "%s: Cannot open file \"%s\" for write\n", strerror(errno), newname);
		DBG_LEAVE("%s: Cannot open file \"%s\" for write", strerror(errno), newname);
		return 1;
	}

	time(&now);

	out_h = NULL;
	//if (!name) {
		DBG_PRINT("Writing to .tmpconfig.h\n");
		out_h = fopen(".tmpconfig.h", "w");
		if (!out_h) {
			fprintf(stderr, "%s: Cannot open file \".tmpconfig.h\" for write\n", strerror(errno));
			DBG_LEAVE("%s: Cannot open file \".tmpconfig.h\" for write", strerror(errno));
			return 1;
	}
		//file_write_dep(NULL);
	//}

	fprintf(out, _("#\n"
		     "# Automatically generated project config: don't edit\n"
		       "#\n"));
	if (out_h)
		fprintf(out_h, "/*\n"
			       " * Automatically generated C config: don't edit\n"
			       " */\n"
			       "#ifndef PRJCONFIG_H\n"
			       "#define PRJCONFIG_H\n\n");

	if (!conf_get_changed())
		sym_clear_all_valid();

	menu = rootmenu.list;
	while (menu) {
		DBG_NL();
		DBG_PRINT("conf_write menu [%s]", DBG_MENU_NAME(menu));
		sym = menu->sym;
		DBG_SYM_DUMP(sym);
		if (!sym) {
			if (!menu_is_visible(menu))
				goto next;
			str = menu_get_prompt(menu);
			fprintf(out, "\n"
				     "#\n"
				     "# %s\n"
				     "#\n", str);
			if (out_h)
				fprintf(out_h, "\n"
					       "/*\n"
					       " * %s\n"
					       " */\n", str);
		} else if (!(sym->flags & SYMBOL_CHOICE)) {
			sym_calc_value(sym);
			if (sym->flags & SYMBOL_TRANSIENT) {
				DBG_PRINT("menu [%s] SYMBOL_TRANSIENT", DBG_MENU_NAME(menu));
				goto next;
			}
			if (!(sym->flags & SYMBOL_WRITE)) {
				DBG_PRINT("menu [%s] SYMBOL_WRITE not set", DBG_MENU_NAME(menu));
				goto next;
			}
			sym->flags &= ~SYMBOL_WRITE;
			type = sym->type;
			DBG_PRINT("menu [%s] type=%d", DBG_MENU_NAME(menu), type);
			if (type == S_TRISTATE) {
				sym_calc_value(modules_sym);
				if (modules_sym->curr.tri == no)
					type = S_BOOLEAN;
			}
			switch (type) {
			case S_BOOLEAN:
			case S_TRISTATE:
				switch (sym_get_tristate_value(sym)) {
				case no:
					fprintf(out, "# CONFIG_%s is not set\n", sym->name);
					if (out_h)
						fprintf(out_h, "#undef CONFIG_%s\n", sym->name);
					break;
				case mod:
					fprintf(out, "CONFIG_%s=m\n", sym->name);
					if (out_h)
						fprintf(out_h, "#define CONFIG_%s_MODULE 1\n", sym->name);
					break;
				case yes:
					fprintf(out, "CONFIG_%s=y\n", sym->name);
					if (out_h)
						fprintf(out_h, "#define CONFIG_%s 1\n", sym->name);
					break;
				}
				break;
			case S_STRING:
				// fix me
				str = sym_get_string_value(sym);
				fprintf(out, "CONFIG_%s=\"", sym->name);
				if (out_h)
					fprintf(out_h, "#define CONFIG_%s \"", sym->name);
				do {
					l = strcspn(str, "\"\\");
					if (l) {
						fwrite(str, l, 1, out);
						if (out_h)
							fwrite(str, l, 1, out_h);
					}
					str += l;
					while (*str == '\\' || *str == '"') {
						fprintf(out, "\\%c", *str);
						if (out_h)
							fprintf(out_h, "\\%c", *str);
						str++;
					}
				} while (*str);
				fputs("\"\n", out);
				if (out_h)
					fputs("\"\n", out_h);
				break;
			case S_HEX:
				str = sym_get_string_value(sym);
				if (str[0] != '0' || (str[1] != 'x' && str[1] != 'X')) {
					fprintf(out, "CONFIG_%s=%s\n", sym->name, str);
					if (out_h)
						fprintf(out_h, "#define CONFIG_%s 0x%s\n", sym->name, str);
					break;
				}
			case S_INT:
				str = sym_get_string_value(sym);
				fprintf(out, "CONFIG_%s=%s\n", sym->name, str);
				if (out_h)
					fprintf(out_h, "#define CONFIG_%s %s\n", sym->name, str);
				break;
			}
		}

	next:
		if (menu->list) {
			menu = menu->list;
			continue;
		}
		if (menu->next)
			menu = menu->next;
		else while ((menu = menu->parent)) {
			if (menu->next) {
				menu = menu->next;
				break;
			}
		}
	}
	fclose(out);
	if (out_h) {
		fprintf(out_h, "\n#endif /* PRJCONFIG_H */\n");
		fclose(out_h);
		DBG_PRINT("renaming .tmpconfig.h to prjconfig.h");
		if (rename(".tmpconfig.h", "prjconfig.h")) {
			fprintf(stderr, "%s: rename %s to %s\n", strerror(errno), ".tmpconfig.h", "prjconfig.h");
			return 1;
		}
	}
	if (!name || basename != conf_get_configname()) {
		if (!name)
			name = conf_get_configname();
		sprintf(tmpname, "%s.old", name);
		if (rename(name, tmpname)) {
			fprintf(stderr, "%s: rename %s to %s\n", strerror(errno), name, tmpname);
			return 1;
		}
	}
	sprintf(tmpname, "%s%s", dirname, basename);
	if (rename(newname, tmpname)) {
		fprintf(stderr, "%s: rename %s to %s\n", strerror(errno), tmpname, newname);
		DBG_LEAVE("rename error %d", errno);
		return 1;
	}

	sym_set_change_count(0);

	file_write_meta_info();

	DBG_LEAVE("OK");
	return 0;
}
static int sym_change_count;
static void (*conf_changed_callback)(void);

void sym_set_change_count(int count)
{
	int _sym_change_count = sym_change_count;
	sym_change_count = count;
	if (conf_changed_callback &&
	    (bool)_sym_change_count != (bool)count)
		conf_changed_callback();
}

void sym_add_change_count(int count)
{
	sym_set_change_count(count + sym_change_count);
}

bool conf_get_changed(void)
{
	return sym_change_count;
}

void conf_set_changed_callback(void (*fn)(void))
{
	conf_changed_callback = fn;
}
