/*
 * Copyright The WildFly Authors
 * SPDX-License-Identifier: Apache-2.0
 */
package org.jboss.as.test.integration.domain;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXCLUDED_EXTENSIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_EXCLUDE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_RESOURCES_OPERATION;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestUtils;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.logging.Logger;
import org.jboss.modules.LocalModuleLoader;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.Resource;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * This test verifies it is possible to get the list of previous release extensions using the host-excludes definition
 * included in the current domain.xml.
 * <p>
 * The test fails if it finds a missing extension in the excluded-extensions section, there is a host-exclude name
 * in domain.xml undefined in this test or we are excluding more extensions than the necessary.
 * <p>
 * It also maintains the configuration of the current release, see ExtensionConf.CURRENT. When an extension is added or
 * removed on the current release, that extension must be tracked down on the ExtensionConf.CURRENT object. Once the
 * current release moves to the next mayor, if the ExtensionConf.CURRENT has extensions added or removed during the
 * current development cycle, the test will fail, forcing us to create new ExtensionConf objects for each previous
 * releases not defined in the test and point out ExtensionConf.CURRENT to the new current release without any
 * additional / removed extensions.
 *
 * @author Yeray Borges
 */
public class HostExcludesTestCase extends BuildConfigurationTestBase {

    private static DomainLifecycleUtil primaryUtils;
    private static DomainClient primaryClient;
    private static WildFlyManagedConfiguration primaryConfig;
    private static final  BiFunction<Set<String>, Set<String>, Set<String>> diff = (a, b) -> a.stream().filter(e -> !b.contains(e)).collect(Collectors.toSet());
    private final boolean isFullDistribution = AssumeTestGroupUtil.isFullDistribution();
    private final boolean isPreviewGalleonPack = AssumeTestGroupUtil.isWildFlyPreview();

    private static final String MAJOR = "8.1";

    /**
     * Maintains the list of expected extensions for each host-exclude name for previous releases.
     * Each enum entry represents the list of extensions that are available on the excluded host.
     * It assumes that the hosts builds are always full builds, including the MP extensions if they exist.
     * This must be corrected on each new host-exclude id added on the current release.
     */
    private enum ExtensionConf {
        // If an extension is added to this enum, also check if it is supplied only by wildfly-galleon-pack. If so, add it also
        // to the internal mpExtensions Set defined on this class.
        // Don't add here extensions supplied only by the wildfly-preview-feature-pack because we are not tracking different releases
        // of wildfly preview. In such a case, add them to previewExtensions set defined below.
        EAP62("EAP62", null, List.of(
                "org.jboss.as.appclient",
                "org.jboss.as.clustering.infinispan",
                "org.jboss.as.clustering.jgroups",
                "org.jboss.as.cmp",
                "org.jboss.as.configadmin",
                "org.jboss.as.connector",
                "org.jboss.as.deployment-scanner",
                "org.jboss.as.ee",
                "org.jboss.as.ejb3",
                "org.jboss.as.jacorb",
                "org.jboss.as.jaxr",
                "org.jboss.as.jaxrs",
                "org.jboss.as.jdr",
                "org.jboss.as.jmx",
                "org.jboss.as.jpa",
                "org.jboss.as.jsf",
                "org.jboss.as.jsr77",
                "org.jboss.as.logging",
                "org.jboss.as.mail",
                "org.jboss.as.messaging",
                "org.jboss.as.modcluster",
                "org.jboss.as.naming",
                "org.jboss.as.pojo",
                "org.jboss.as.remoting",
                "org.jboss.as.sar",
                "org.jboss.as.security",
                "org.jboss.as.threads",
                "org.jboss.as.transactions",
                "org.jboss.as.web",
                "org.jboss.as.webservices",
                "org.jboss.as.weld",
                "org.jboss.as.xts",
                // This module was added in EAP70, but we move it to the EAP62 extension list to allow the test passing
                // without adding it to the host-exclude section. We don't want to expose it in the host-exclude.
                "org.wildfly.extension.mod_cluster"
        ), false),
        EAP63("EAP63", EAP62, List.of(
                "org.wildfly.extension.picketlink"
        ), false),
        EAP64("EAP64", EAP63, false),
        EAP64z("EAP64z", EAP64, false),
        EAP70("EAP70", EAP64z, List.of(
                "org.wildfly.extension.batch.jberet",
                "org.wildfly.extension.bean-validation",
                "org.wildfly.extension.clustering.singleton",
                "org.wildfly.extension.io",
                "org.wildfly.extension.messaging-activemq",
                "org.wildfly.extension.request-controller",
                "org.wildfly.extension.rts",
                "org.wildfly.extension.security.manager",
                "org.wildfly.extension.undertow",
                "org.wildfly.iiop-openjdk"
        ), false),
        EAP71("EAP71", EAP70, List.of(
                "org.wildfly.extension.core-management",
                "org.wildfly.extension.discovery",
                "org.wildfly.extension.elytron"
        ), false),
        EAP72("EAP72", EAP71, List.of(
                "org.wildfly.extension.datasources-agroal",
                "org.wildfly.extension.microprofile.opentracing-smallrye",
                "org.wildfly.extension.microprofile.health-smallrye",
                "org.wildfly.extension.microprofile.config-smallrye",
                "org.wildfly.extension.ee-security"
        ), false),
        EAP73("EAP73", EAP72, List.of(
                "org.wildfly.extension.microprofile.metrics-smallrye",
                "org.wildfly.extension.clustering.web"
        ), false),
        EAP74("EAP74", EAP73, List.of(
                "org.wildfly.extension.health",
                "org.wildfly.extension.metrics",
                "org.wildfly.extension.microprofile.fault-tolerance-smallrye",
                "org.wildfly.extension.microprofile.jwt-smallrye",
                "org.wildfly.extension.microprofile.openapi-smallrye",
                "org.wildfly.extension.microprofile.reactive-messaging-smallrye",
                "org.wildfly.extension.microprofile.reactive-streams-operators-smallrye"
        ), true),
        EAP80("EAP80", EAP74, List.of(
                "org.wildfly.extension.clustering.ejb",
                "org.wildfly.extension.elytron-oidc-client",
                "org.wildfly.extension.micrometer",
                "org.wildfly.extension.microprofile.lra-coordinator",
                "org.wildfly.extension.microprofile.lra-participant",
                "org.wildfly.extension.opentelemetry",
                "org.wildfly.extension.microprofile.telemetry"
        ), List.of(
                "org.jboss.as.cmp",
                "org.jboss.as.jaxr",
                "org.jboss.as.configadmin",
                "org.jboss.as.jacorb",
                "org.jboss.as.messaging",
                "org.jboss.as.web"
        ), true),
        // If an extension is added to this enum, also check if it is supplied only by wildfly-galleon-pack. If so, add it also
        // to the internal mpExtensions Set defined on this class.
        // Don't add here extensions supplied only by the wildfly-preview-feature-pack because we are not tracking different releases
        // of wildfly preview. In such a case, add them to previewExtensions set defined below.
        CURRENT(MAJOR, EAP80, true);

        private final String name;
        private final ExtensionConf parent;
        private final Set<String> extensions = new HashSet<>();
        private final Set<String> removed = new HashSet<>();
        private static final Map<String, ExtensionConf> MAP;
        private final boolean modified;
        private final boolean supported;

        // List of extensions added by the wildfly-galleon-pack
        private final Set<String> expansionExtensions = new HashSet<>(Arrays.asList(
                "org.wildfly.extension.micrometer",
                "org.wildfly.extension.microprofile.config-smallrye",
                "org.wildfly.extension.microprofile.health-smallrye",
                "org.wildfly.extension.microprofile.metrics-smallrye",
                "org.wildfly.extension.microprofile.fault-tolerance-smallrye",
                "org.wildfly.extension.microprofile.jwt-smallrye",
                "org.wildfly.extension.microprofile.openapi-smallrye",
                "org.wildfly.extension.microprofile.opentracing-smallrye",
                "org.wildfly.extension.microprofile.reactive-messaging-smallrye",
                "org.wildfly.extension.microprofile.reactive-streams-operators-smallrye",
                "org.wildfly.extension.microprofile.lra-coordinator",
                "org.wildfly.extension.microprofile.lra-participant",
                "org.wildfly.extension.microprofile.telemetry",
                "org.wildfly.extension.opentelemetry"
        ));

        // List of extensions added only by WildFly Preview.
        // We do not track changes between different versions of WildFly Preview.
        // From the point of view of this test, all extensions added in WildFly Preview are always extensions
        // added in the latest release of WildFly Preview. It is out of the scope of Host Exclusion test
        // to compute on which WildFly Preview was added such a new extension and track the Host Exclusions between
        // different WildFly Preview releases.
        private final Set<String> previewExtensions = new HashSet<>(Arrays.asList(
                "org.wildfly.extension.jakarta.data",
                "org.wildfly.extension.vertx",
                "org.wildfly.extension.mvc-krazo"
        ));

        ExtensionConf(String name, ExtensionConf parent, boolean supported) {
            this(name, parent, null, null, supported);
        }

        ExtensionConf(String name, ExtensionConf parent, List<String> addedExtensions, boolean supported) {
            this(name, parent, addedExtensions, null, supported);
        }

        /**
         * Main constructor
         *  @param name Host exclude name to define
         * @param parent A parent extension definition
         * @param addedExtensions Extensions added on the server release referred by this host exclude name
         * @param removedExtensions Extensions removed on the server release referred by this host exclude name
         * @param supported whether the given release is supported as a secondary host in a mixed domain
         */
        ExtensionConf(String name, ExtensionConf parent, List<String> addedExtensions, List<String> removedExtensions, boolean supported) {
            this.name = name;
            this.parent = parent;
            this.modified = (addedExtensions != null && !addedExtensions.isEmpty()) || (removedExtensions != null && !removedExtensions.isEmpty());
            if (addedExtensions != null) {
                this.extensions.addAll(addedExtensions);
            }
            if (parent != null) {
                this.extensions.addAll(parent.extensions);
                this.removed.addAll(parent.removed);
            }
            if (removedExtensions != null) {
                this.extensions.removeAll(removedExtensions);
                this.removed.addAll(removedExtensions);
            }
            this.supported = supported;
        }

        static {
            final Map<String, ExtensionConf> map = new HashMap<>();
            for (ExtensionConf element : values()) {
                final String name = element.name;
                if (name != null) map.put(name, element);
            }
            MAP = map;
        }

        public static ExtensionConf forName(String name) {
            return MAP.get(name);
        }

        public Set<String> getRemovedExtensions() {
            return removed;
        }

        public Set<String> getExtensions(boolean isFullDistribution, boolean isPreview) {
            if (this.name.equals(MAJOR) && isPreview) {
                this.extensions.addAll(previewExtensions);
            }
            if (!isFullDistribution && !isPreview) {
                return diff.apply(extensions, expansionExtensions);
            }
            return extensions;
        }

        public boolean isModified() {
            return modified;
        }

        public boolean isSupported() {
            return supported;
        }

        public String getName() {
            return name;
        }
    }

    // Extensions that are only available for standalone mode and as a such won't be usable in domain mode
    private final Set<String> standaloneOnlyExtensions = new HashSet<>(List.of(
            "org.keycloak.keycloak-adapter-subsystem"
    ));

    @BeforeClass
    public static void setUp() throws IOException {
        primaryConfig = createConfiguration("domain.xml", "host-primary.xml", HostExcludesTestCase.class.getSimpleName());
        primaryUtils = new DomainLifecycleUtil(primaryConfig);
        primaryUtils.start();
        primaryClient = primaryUtils.getDomainClient();
    }

    @AfterClass
    public static void tearDown() {
        if (primaryUtils != null) {
            primaryUtils.stop();
        }
    }

    @Test
    public void testHostExcludes() throws IOException, MgmtOperationException {
        Set<String> availableExtensions = retrieveAvailableExtensions();
        availableExtensions.removeAll(standaloneOnlyExtensions);

        ModelNode op = Util.getEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, null);
        op.get(CHILD_TYPE).set(EXTENSION);

        ModelNode result = DomainTestUtils.executeForResult(op, primaryClient);

        Set<String> currentExtensions = new HashSet<>();
        for (Property prop : result.asPropertyList()) {
            currentExtensions.add(prop.getName());
        }

        //Check we are able to retrieve at minimum all the extensions defined for the current server
        if (!availableExtensions.containsAll(currentExtensions)) {
            currentExtensions.removeAll(availableExtensions);
            fail(String.format("The following extensions defined in domain.xml cannot be retrieved by this test %s . " +
                    "It could lead in a false negative test result, check HostExcludesTestCase.retrieveAvailableExtensions method", currentExtensions));
        }

        // Check that the list of all available extensions is in the ExtensionConf.CURRENT configuration
        Set<String> current = ExtensionConf.forName(MAJOR).getExtensions(isFullDistribution, isPreviewGalleonPack);
        if (!current.equals(availableExtensions)) {
            Set<String> extensionsAdded = diff.apply(current, availableExtensions);
            Set<String> extensionsRemoved = diff.apply(availableExtensions, current);
            fail(String.format("The following extensions %s have been removed on the current release. Remove them on ExtensionConf.CURRENT object defined in this test. " +
                    "The following extensions %s have been added on the current release. Add them to ExtensionConf.CURRENT object defined in this test.", extensionsAdded, extensionsRemoved));
        }

        // If the ExtensionConf.CURRENT has extensions removed / added and the version it represents no longer
        // points out to the actual, then we need to create new ExtensionConf(s) for each of the previous releases
        // not included in this test.
        if (ExtensionConf.CURRENT.isModified()) {
            op = Util.getReadAttributeOperation(null, "product-version");
            result = DomainTestUtils.executeForResult(op, primaryClient);
            if (!result.asString().startsWith(ExtensionConf.CURRENT.getName())) {
                fail(String.format("The ExtensionConf.CURRENT has extensions added or removed but it no longer points to the current release. " +
                        "Modify this test adding new ExtensionConf enums for each previous releases undefined in this test by using the list of extensions added or removed on ExtensionConf.CURRENT." +
                        "Then remove all the extensions from ExtensionConf.CURRENT enum and correct the MAJOR number accordingly to point out to the current release."));
            }
        }

        op = Util.getEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, null);
        op.get(CHILD_TYPE).set(HOST_EXCLUDE);

        result = DomainTestUtils.executeForResult(op, primaryClient);

        Set<String> processedExclusionsIds = new HashSet<>();
        for (Property prop : result.asPropertyList()) {
            String name = prop.getName();

            List<String> excludedExtensions = prop.getValue().get(EXCLUDED_EXTENSIONS)
                    .asListOrEmpty()
                    .stream()
                    .map(ModelNode::asString)
                    .collect(Collectors.toList());

            //check duplicated extensions
            Assert.assertEquals(String.format("There are duplicated extensions declared for %s host-exclude", name),
                    excludedExtensions.size(),
                    new HashSet<>(excludedExtensions).size()
            );

            //check we have defined the current host-exclude configuration in the test
            ExtensionConf confPrevRelease = ExtensionConf.forName(name);
            Assert.assertNotNull(String.format(
                            "This host-exclude name is not defined in this test: %s", name),
                    confPrevRelease);

            //check that available extensions - excluded extensions = expected extensions in a previous release - removed
            Set<String> expectedExtensions = ExtensionConf.forName(name).getExtensions(isFullDistribution, isPreviewGalleonPack);
            expectedExtensions.removeAll(ExtensionConf.forName(MAJOR).getRemovedExtensions());

            Set<String> extensionsUnderTest = new HashSet<>(availableExtensions);
            extensionsUnderTest.removeAll(excludedExtensions);

            if (expectedExtensions.size() > extensionsUnderTest.size()) {
                expectedExtensions.removeAll(extensionsUnderTest);
                fail(String.format("These extensions are expected to be available after applying the %s host-exclude configuration to the extensions supplied by this server release: %s", name, expectedExtensions));
            }

            if ( extensionsUnderTest.size() != expectedExtensions.size() ){
                extensionsUnderTest.removeAll(expectedExtensions);
                fail(String.format("These extensions are missing on the %s host-exclude: %s", name, extensionsUnderTest));
            }

            processedExclusionsIds.add(name);
        }

        // Verifies all the exclusions Id added as configurations for this test are defined as host exclusions in the current server release
        for(ExtensionConf extensionConf : ExtensionConf.values()) {
            if (extensionConf != ExtensionConf.CURRENT && extensionConf.isSupported() && !processedExclusionsIds.contains(extensionConf.getName())) {
                Set<String> extensions = extensionConf.getExtensions(isFullDistribution, isPreviewGalleonPack);
                ExtensionConf major = ExtensionConf.forName(MAJOR);
                extensions.removeAll(major.getRemovedExtensions());
                if (!extensions.equals(availableExtensions)) {
                    boolean fail = !isPreviewGalleonPack;
                    if (!fail) {
                        // If a preview-only extension remains preview-only beyond its initial release, there may be
                        // no host-exclude for its initial release, if nothing else added later needed an exclude
                        // for that release. But it also won't be in 'extensions'. We don't want to track in which
                        // release it arrived, so for any version between current and the first one where we have
                        // a host-exclude, treat it as if it were present.
                        // This opens the possibility of this test missing that the developer added the extension
                        // to existing host-exclude entries but forgot to add a new host-exclude,
                        // but the alternative is complete tracking of when extensions come and go from WFP.
                        fail = true;
                        ExtensionConf conf = major;
                        while (conf != null && !processedExclusionsIds.contains(conf.getName())) {
                            if (conf == extensionConf) {
                                extensions.addAll(major.previewExtensions);
                                fail = !extensions.equals(availableExtensions);
                                break;
                            }
                            conf = conf.parent;
                        }
                    }
                    if (fail) {
                        fail(String.format("The %s exclusion id is not defined as host exclusion for the current release. Extension diff: %s",
                                extensionConf.getName(), diff.apply(availableExtensions, extensions)));
                    }
                }
            }
        }
    }

    /**
     * Retrieve the list of all modules which export locally a resource that implements org.jboss.as.controller.Extension.
     * This list is considered the list of all available extensions that can be added to a server.
     *
     * It is assumed that the module which is added as an extension has the org.jboss.as.controller.Extension service as
     * a local resource.
     */
    private Set<String> retrieveAvailableExtensions() throws IOException {
        final Set<String> result = new HashSet<>();
        LocalModuleLoader ml = new LocalModuleLoader(getModuleRoots());
        Iterator<String> moduleNames = ml.iterateModules((String) null, true);
        while (moduleNames.hasNext()) {
            String moduleName = moduleNames.next();
            if (moduleName.equals("org.wildfly.extension.elytron.jaas-realm")) {
                // Temporary workaround until https://issues.redhat.com/browse/WFCORE-6834 gets fixed
                // org.wildfly.extension.elytron.jaas-realm is not a WildFly extension, so even if it supplies
                // a META-INF/services/org.jboss.as.controller.Extension file, we should ignore it.
                continue;
            }
            Module module;
            try {
                module = ml.loadModule(moduleName);
                List<Resource> resources = module.getClassLoader().loadResourceLocal("META-INF/services/org.jboss.as.controller.Extension");
                if (!resources.isEmpty()) {
                    result.add(moduleName);
                }
            } catch (ModuleLoadException e) {
                Logger.getLogger(HostExcludesTestCase.class).warn("Failed to load module " + moduleName +
                        " to check if it is an extension", e);
            }
        }
        return result;
    }

    private static File[] getModuleRoots() throws IOException {
        Path layersRoot = Paths.get(primaryConfig.getModulePath()) .resolve("system").resolve("layers");
        DirectoryStream.Filter<Path> filter = entry -> {
            File f = entry.toFile();
            return f.isDirectory() && !f.isHidden();
        };
        List<File> result = new ArrayList<>();
        try(DirectoryStream<Path> stream = Files.newDirectoryStream(layersRoot, filter)) {
            for (Path path : stream) {
                result.add(path.toFile());
            }
        }
        return result.toArray(new File[0]);
    }
}
