/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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
 *
 *     http://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.jboss.installer.postinstall.task;

import org.apache.commons.io.FileUtils;
import org.jboss.installer.core.InstallationData;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.postinstall.server.DomainServer;
import org.jboss.installer.test.utils.TestServer;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import static org.jboss.installer.test.utils.TestServer.TARGET_PATH;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class Ipv6EnabledTaskTest {

    @Rule
    public TestServer testServer = new TestServer();

    private TaskPrinter printer = new NoopPrinter();

    @Test
    public void replaceLocalhostReferencesInStandaloneXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TARGET_PATH);

        new Ipv6EnabledTask().applyToInstallation(idata, printer);

        assertLocalhostReplaced("standalone.xml");
        assertLocalhostReplaced("standalone-ha.xml");
        assertLocalhostReplaced("standalone-full.xml");
        assertLocalhostReplaced("standalone-full-ha.xml");
        assertLocalhostReplaced("domain.xml");
        assertLocalhostReplaced("host.xml");
        assertLocalhostReplaced(DomainServer.HOST_PRIMARY_XML);
        assertLocalhostReplaced(DomainServer.HOST_SECONDARY_XML);
        assertLocalhostReplaced("appclient.xml");

        for (String conf: Ipv6EnabledTask.REQUIRED_CONFIGS) {
            assertPreferredStackReplaced(conf);
        }
        for (String conf: Ipv6EnabledTask.OPTIONAL_CONFIGS) {
            assertPreferredStackReplaced(conf);
        }
        assertPreferredStackReplacedInDomain();

        assertPreferredStackAppendedToWindowsCliScript();
        assertPreferredStackAppendedToPowershellCliScript();
    }

    @Test
    public void skipMissingOptionalFile() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TARGET_PATH);

        FileUtils.deleteDirectory(TARGET_PATH.resolve("appclient").toFile());

        new Ipv6EnabledTask().applyToInstallation(idata, printer);
    }

    private void assertPreferredStackAppendedToWindowsCliScript() throws Exception {
        final List<String> lines = Files.readAllLines(TARGET_PATH.resolve("bin").resolve("jboss-cli.bat"));
        assertTextPresent("jboss-cli.bat", lines, "-Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true");
    }

    private void assertPreferredStackAppendedToPowershellCliScript() throws Exception {
        final List<String> lines = Files.readAllLines(TARGET_PATH.resolve("bin").resolve("jboss-cli.ps1"));
        assertTextPresent("jboss-cli.ps1", lines, "-Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true");
    }

    private void assertPreferredStackReplacedInDomain() throws Exception {
        final List<String> lines = Files.readAllLines(TARGET_PATH.resolve("domain").resolve("configuration").resolve("domain.xml"));
        assertTextNotPresent("domain.xml", lines, "<property name=\"java.net.preferIPv4Stack\" value=\"true\"/>");
        assertTextPresent("domain.xml", lines, "<property name=\"java.net.preferIPv6Addresses\" value=\"true\"/>");
    }

    private void assertPreferredStackReplaced(String conf) throws Exception {
        final List<String> lines = Files.readAllLines(TARGET_PATH.resolve("bin").resolve(conf));
        assertTextNotPresent(conf, lines, "-Djava.net.preferIPv4Stack=true");
        assertTextPresent(conf, lines, "-Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses");
    }

    private void assertLocalhostReplaced(String fileName) throws IOException {
        final String folder;
        if (fileName.startsWith("standalone")) {
            folder = "standalone";
        } else if (fileName.startsWith("domain") || fileName.startsWith("host")) {
            folder = "domain";
        } else if (fileName.startsWith("appclient")) {
            folder = "appclient";
        } else {
            throw new IllegalArgumentException("Unknown file " + fileName);
        }

        final List<String> lines = Files.readAllLines(TARGET_PATH.resolve(folder).resolve("configuration").resolve(fileName));
        assertTextNotPresent(fileName, lines, "127.0.0.1");
    }

    private void assertTextPresent(String conf, List<String> lines, String s) {
        assertTrue("Text " + s + " not present in " + conf, lines.stream().anyMatch(l -> l.contains(s)));
    }

    private void assertTextNotPresent(String conf, List<String> lines, String s) {
        assertFalse("Text " + s + " present in " + conf, lines.stream().anyMatch(l -> l.contains(s)));
    }
}
