/* Copyright (c) Dovecot authors, see top-level COPYING file */

#include "test-auth.h"
#include "test-dir.h"
#include "auth-common.h"
#include "settings.h"
#include "auth-settings.h"
#include "auth-token.h"
#include "auth-penalty.h"
#include "sasl-server.h"
#include "db-oauth2.h"
#include "passdb.h"
#include "userdb.h"

#include <time.h>

static const char *const settings[] = {
	"auth_mechanisms",
		"ANONYMOUS APOP CRAM-MD5 DIGEST-MD5 EXTERNAL LOGIN PLAIN "
		"OAUTHBEARER SCRAM-SHA-1 SCRAM-SHA-256 XOAUTH2",
	"auth_username_chars", "",
	"auth_username_format", "",
	/* For tests of digest-md5. */
	"auth_realms", "example.com",
	/* For tests of mech-anonymous. */
	"auth_anonymous_username", "anonuser",
	/* For oauth2 tests */
	"oauth2_introspection_mode", "auth",
	"oauth2_tokeninfo_url", "http://localhost",
	"oauth2_client_id", "foo",
	"oauth2_client_secret", "foo",
	"oauth2_use_worker", "no",

	"passdb", "mock1 mock2",
	"passdb/mock1/name", "mock1",
	"passdb/mock1/driver", "mock",
	"passdb/mock2/name", "mock1",
	"passdb/mock2/driver", "mock",
	"passdb/mock2/master", "yes",

	NULL
};

static struct settings_simple simple_set;

void test_auth_init(void)
{
	const char *const protocols[] = {NULL};
	process_start_time = time(NULL);
	test_dir_init("test-auth");

	settings_simple_init(&simple_set, settings);
	settings_override(simple_set.instance, "base_dir", test_dir_get(), SETTINGS_OVERRIDE_TYPE_CLI_PARAM);
	global_auth_settings = settings_get_or_fatal(simple_set.event,
						     &auth_setting_parser_info);
	/* this is needed to get oauth2 initialized */
	auth_event = simple_set.event;
	passdbs_init();
	userdbs_init();
	passdb_mock_mod_init();
	password_schemes_register_all();
	password_schemes_allow_weak(TRUE);

	auth_sasl_preinit(global_auth_settings);
	auths_preinit(simple_set.event, global_auth_settings, protocols);
	auths_init();
	auth_token_init();
	auth_sasl_init();

	auth_penalty = auth_penalty_init("missing");
}

void test_auth_deinit(void)
{
	auth_penalty_deinit(&auth_penalty);
	db_oauth2_deinit();
	auths_deinit();
	auth_token_deinit();
	password_schemes_deinit();
	passdb_mock_mod_deinit();
	passdbs_deinit();
	userdbs_deinit();
	event_unref(&auth_event);
	auths_free();
	auth_sasl_deinit();
	settings_free(global_auth_settings);
	settings_simple_deinit(&simple_set);
	i_unlink_if_exists("auth-token-secret.dat");
}
