/*
 * Copyright 2012-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.ldap.autoconfigure.embedded;

import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;

import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.schema.Schema;
import com.unboundid.ldif.LDIFReader;
import org.jspecify.annotations.Nullable;

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Builder;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.ldap.autoconfigure.LdapAutoConfiguration;
import org.springframework.boot.ldap.autoconfigure.LdapProperties;
import org.springframework.boot.ldap.autoconfigure.embedded.EmbeddedLdapAutoConfiguration.EmbeddedLdapAutoConfigurationRuntimeHints;
import org.springframework.boot.ldap.autoconfigure.embedded.EmbeddedLdapProperties.Ssl;
import org.springframework.boot.ssl.SslBundle;
import org.springframework.boot.ssl.SslBundles;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for Embedded LDAP.
 *
 * @author Eddú Meléndez
 * @author Mathieu Ouellet
 * @author Raja Kolli
 * @since 4.0.0
 */
@AutoConfiguration(before = LdapAutoConfiguration.class)
@EnableConfigurationProperties({ LdapProperties.class, EmbeddedLdapProperties.class })
@ConditionalOnClass(InMemoryDirectoryServer.class)
@Conditional(EmbeddedLdapAutoConfiguration.EmbeddedLdapCondition.class)
@ImportRuntimeHints(EmbeddedLdapAutoConfigurationRuntimeHints.class)
public final class EmbeddedLdapAutoConfiguration implements DisposableBean {

	private static final String PROPERTY_SOURCE_NAME = "ldap.ports";

	private final EmbeddedLdapProperties embeddedProperties;

	private @Nullable InMemoryDirectoryServer server;

	EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties) {
		this.embeddedProperties = embeddedProperties;
	}

	@Bean
	InMemoryDirectoryServer directoryServer(ApplicationContext applicationContext,
			ObjectProvider<SslBundles> sslBundles) throws LDAPException {
		String[] baseDn = StringUtils.toStringArray(this.embeddedProperties.getBaseDn());
		InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(baseDn);
		String username = this.embeddedProperties.getCredential().getUsername();
		String password = this.embeddedProperties.getCredential().getPassword();
		if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
			config.addAdditionalBindCredentials(username, password);
		}
		config.setListenerConfigs(createListenerConfig(sslBundles));
		setSchema(config);
		this.server = new InMemoryDirectoryServer(config);
		importLdif(this.server, applicationContext);
		this.server.startListening();
		setPortProperty(applicationContext, this.server.getListenPort());
		return this.server;
	}

	private InMemoryListenerConfig createListenerConfig(ObjectProvider<SslBundles> sslBundles) throws LDAPException {
		SslBundle sslBundle = getSslBundle(sslBundles.getIfAvailable());
		if (sslBundle != null) {
			SSLContext sslContext = sslBundle.createSslContext();
			SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
			SSLSocketFactory clientSocketFactory = sslContext.getSocketFactory();
			return InMemoryListenerConfig.createLDAPSConfig("LDAPS", null, this.embeddedProperties.getPort(),
					serverSocketFactory, clientSocketFactory);
		}
		return InMemoryListenerConfig.createLDAPConfig("LDAP", this.embeddedProperties.getPort());
	}

	private @Nullable SslBundle getSslBundle(@Nullable SslBundles sslBundles) {
		Ssl ssl = this.embeddedProperties.getSsl();
		if (ssl.isEnabled() && StringUtils.hasLength(ssl.getBundle())) {
			Assert.notNull(sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
			return sslBundles.getBundle(ssl.getBundle());
		}
		return null;
	}

	private void setSchema(InMemoryDirectoryServerConfig config) {
		if (!this.embeddedProperties.getValidation().isEnabled()) {
			config.setSchema(null);
			return;
		}
		Resource schema = this.embeddedProperties.getValidation().getSchema();
		if (schema != null) {
			setSchema(config, schema);
		}
	}

	private void setSchema(InMemoryDirectoryServerConfig config, Resource resource) {
		try {
			Schema defaultSchema = Schema.getDefaultStandardSchema();
			Schema schema = Schema.getSchema(resource.getInputStream());
			if (schema == null) {
				config.setSchema(defaultSchema);
			}
			else {
				config.setSchema(Schema.mergeSchemas(defaultSchema, schema));
			}
		}
		catch (Exception ex) {
			throw new IllegalStateException("Unable to load schema " + resource.getDescription(), ex);
		}
	}

	private void importLdif(InMemoryDirectoryServer server, ApplicationContext applicationContext) {
		String location = this.embeddedProperties.getLdif();
		if (StringUtils.hasText(location)) {
			try {
				Resource resource = applicationContext.getResource(location);
				if (resource.exists()) {
					try (InputStream inputStream = resource.getInputStream()) {
						server.importFromLDIF(true, new LDIFReader(inputStream));
					}
				}
			}
			catch (Exception ex) {
				throw new IllegalStateException("Unable to load LDIF " + location, ex);
			}
		}
	}

	private void setPortProperty(ApplicationContext context, int port) {
		if (context instanceof ConfigurableApplicationContext configurableContext) {
			MutablePropertySources sources = configurableContext.getEnvironment().getPropertySources();
			getLdapPorts(sources).put("local.ldap.port", port);
		}
		if (context.getParent() != null) {
			setPortProperty(context.getParent(), port);
		}
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> getLdapPorts(MutablePropertySources sources) {
		PropertySource<?> propertySource = sources.get(PROPERTY_SOURCE_NAME);
		if (propertySource == null) {
			propertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, new HashMap<>());
			sources.addFirst(propertySource);
		}
		return (Map<String, Object>) propertySource.getSource();
	}

	@Override
	public void destroy() throws Exception {
		if (this.server != null) {
			this.server.shutDown(true);
		}
	}

	/**
	 * {@link SpringBootCondition} to determine when to apply embedded LDAP
	 * auto-configuration.
	 */
	static class EmbeddedLdapCondition extends SpringBootCondition {

		private static final Bindable<List<String>> STRING_LIST = Bindable.listOf(String.class);

		@Override
		public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
			Builder message = ConditionMessage.forCondition("Embedded LDAP");
			Environment environment = context.getEnvironment();
			if (environment != null && !Binder.get(environment)
				.bind("spring.ldap.embedded.base-dn", STRING_LIST)
				.orElseGet(Collections::emptyList)
				.isEmpty()) {
				return ConditionOutcome.match(message.because("Found base-dn property"));
			}
			return ConditionOutcome.noMatch(message.because("No base-dn property found"));
		}

	}

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(ContextSource.class)
	static class EmbeddedLdapContextConfiguration {

		@Bean
		@DependsOn("directoryServer")
		@ConditionalOnMissingBean
		LdapContextSource ldapContextSource(Environment environment, LdapProperties properties,
				EmbeddedLdapProperties embeddedProperties) {
			LdapContextSource source = new LdapContextSource();
			source.setBase(properties.getBase());
			String username = embeddedProperties.getCredential().getUsername();
			String password = embeddedProperties.getCredential().getPassword();
			if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
				source.setUserDn(username);
				source.setPassword(password);
			}
			source.setUrls(properties.determineUrls(environment));
			return source;
		}

	}

	static class EmbeddedLdapAutoConfigurationRuntimeHints implements RuntimeHintsRegistrar {

		@Override
		public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
			hints.resources()
				.registerPatternIfPresent(classLoader, "schema.ldif", (hint) -> hint.includes("schema.ldif"));
		}

	}

}
