/*
	Copyright (c) 2010 by Dennis Schridde

	This file is part of dovecot-metadata.

	dovecot-metadata is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	dovecot-metadata is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with dovecot-metadata.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "metadata-settings.h"

#include <stdlib.h>

#define METADATA_MAXSIZE_DEFAULT 1024
#define METADATA_MAXENTRIES_DEFAULT 65536

void
metadata_settings_init(struct metadata_settings **set, struct mail_user *user) {
	*set = i_new(struct metadata_settings, 1);
	memset(*set, 0, sizeof(**set));


	const char *dict_uri = mail_user_plugin_getenv(user, "metadata_dict");
	if (dict_uri != NULL) {
		(*set)->dict_uri = dict_uri;
	}
	else if (user->mail_debug) {
		i_debug("metadata: No metadata_dict setting - "
			"metadata storage is disabled");
		(*set)->dict_uri = NULL;
	}

	const char *maxsize = mail_user_plugin_getenv(user, "metadata_maxsize");
	if (maxsize != NULL) {
		(*set)->maxsize = strtol(maxsize, NULL, 10);
		if ((*set)->maxsize < 0 || (*set)->maxsize == LONG_MAX) {
			if (user->mail_debug) {
				i_debug("metadata: Illegal metadata_maxsize setting - "
					"using default of %d", METADATA_MAXSIZE_DEFAULT);
			}
			(*set)->maxsize = METADATA_MAXSIZE_DEFAULT;
		}
	}
	else {
		if (user->mail_debug) {
			i_debug("metadata: No metadata_maxsize setting - "
				"using default of %d", METADATA_MAXSIZE_DEFAULT);
		}
		(*set)->maxsize = METADATA_MAXSIZE_DEFAULT;
	}

	const char *maxentries = mail_user_plugin_getenv(user, "metadata_maxentries");
	if (maxentries != NULL) {
		(*set)->maxentries = strtol(maxentries, NULL, 10);
		if ((*set)->maxentries < 0 || (*set)->maxentries == LONG_MAX) {
			if (user->mail_debug) {
				i_debug("metadata: Illegal metadata_maxentries setting - "
					"using default of %d", METADATA_MAXENTRIES_DEFAULT);
			}
			(*set)->maxentries = METADATA_MAXENTRIES_DEFAULT;
		}
	}
	else {
		if (user->mail_debug) {
			i_debug("metadata: No metadata_maxentries setting - "
				"using default of %d", METADATA_MAXENTRIES_DEFAULT);
		}
		(*set)->maxentries = METADATA_MAXENTRIES_DEFAULT;
	}
}

void
metadata_settings_deinit(struct metadata_settings **set) {
	free(*set);
	*set = NULL;
}
