/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2012, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This 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 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.as.config.assembly;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.jboss.as.config.assembly.ModuleParser.ModuleDependency;
import org.jboss.modules.ModuleIdentifier;

/**
 * Generate module directory pattern file as used by FileSet.includes
 * file http://ant.apache.org/manual/Types/fileset.html
 *
 * @author Thomas.Diesler@jboss.com
 * @since 06-Sep-2012
 */
public class GenerateModulesDefinition {

    static final String SPLIT_PATTERN = ",(\\s*)";
    static final String SKIP_SUBSYSTEMS = "skip-subsystems";
    static final String NO_MODULE_DEPENENCIES = "no-module-dependencies";

    private final File inputFile;
    private final String profile;
    private final File resourcesDir;
    private final String[] staticModules;
    private final File outputFile;

    /**
     * arg[0] - subsystems definition file as generated by {@link GenerateSubsystemsDefinition}
     * arg[1] - subsytem profile (e.g. default)
     * arg[2] - resources directory for server definitions (e.g. jboss-as/build/src/main/resources)
     * arg[3] - a comma seperated list of modules to include (e.g. org.jboss.as.standalone,org.jboss.as.console)
     * arg[4] - the output file (e.g. target/module-dependencies.txt)
     */
    public static void main(String[] args) throws Exception {
        if (args == null)
            throw new IllegalArgumentException("Null args");
        if (args.length < 5)
            throw new IllegalArgumentException("Invalid args: " + Arrays.asList(args));

        int index = 0;
        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No input file");
        }
        File inputFile = new File(args[index++]);

        if (args[index] == null) {
            throw new IllegalArgumentException("No profile");
        }
        String profile = args[index++];

        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No resources dir");
        }
        File resourcesDir = new File(args[index++]);

        String[] staticModules = new String[] {};
        if (args[index] != null && !args[index].isEmpty()) {
            staticModules = args[index].trim().split(SPLIT_PATTERN);
        }
        index++;

        if (args[index] == null || args[index].isEmpty()) {
            throw new IllegalArgumentException("No output file");
        }
        File outputFile = new File(args[index]);

        new GenerateModulesDefinition(inputFile, profile, resourcesDir, staticModules, outputFile).process();
    }

    private GenerateModulesDefinition(File inputFile, String profile, File resourcesDir, String[] staticModules, File outputFile) {
        this.inputFile = inputFile;
        this.profile = profile;
        this.resourcesDir = resourcesDir;
        this.staticModules = staticModules;
        this.outputFile = outputFile;
    }

    private void process() throws XMLStreamException, IOException {

        ElementNode modulesNode = new ElementNode(null, "modules", "urn:modules:1.0");
        List<ModuleIdentifier> dependencies = new ArrayList<ModuleIdentifier>();

        if (!inputFile.getName().equals(SKIP_SUBSYSTEMS)) {
            SubsystemsParser parser = new SubsystemsParser(inputFile);
            parser.parse();

            for (SubsystemConfig config : parser.getSubsystemConfigs().get(profile)) {
                File configFile = new File(resourcesDir + File.separator + config.getSubsystem());
                SubsystemParser configParser = new SubsystemParser(null, config.getSupplement(), configFile);
                configParser.parse();

                ModuleIdentifier moduleId = ModuleIdentifier.create(configParser.getExtensionModule());
                processModuleDependency(dependencies, modulesNode, new ModuleDependency(moduleId, false));
            }
        }

        for (String staticId : staticModules) {
            if (!staticId.isEmpty()) {
                ModuleIdentifier moduleId = ModuleIdentifier.fromString(staticId);
                processModuleDependency(dependencies, modulesNode, new ModuleDependency(moduleId, false));
            }
        }

        // sort the dependencies
        Comparator<ModuleIdentifier> comp = new Comparator<ModuleIdentifier>() {
            @Override
            public int compare(ModuleIdentifier o1, ModuleIdentifier o2) {
                return o1.toString().compareTo(o2.toString());
            }
        };
        Collections.sort(dependencies, comp);

        PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
        try {
            if (!dependencies.isEmpty()) {
                for (ModuleIdentifier moduleId : dependencies) {
                    String path = moduleId.getName().replace('.', '/') + File.separator + moduleId.getSlot();
                    pw.println(path + File.separator + "**");
                }
            } else {
                pw.println(NO_MODULE_DEPENENCIES);
            }
        } finally {
            pw.close();
        }

        String xmloutput = outputFile.getPath();
        Writer writer = new FileWriter(xmloutput.substring(0, xmloutput.lastIndexOf(".")) + ".xml");
        try {
            XMLOutputFactory factory = XMLOutputFactory.newInstance();
            XMLStreamWriter xmlwriter = new FormattingXMLStreamWriter(factory.createXMLStreamWriter(writer));
            modulesNode.marshall(xmlwriter);
        } finally {
            writer.close();
        }
    }

    private void processModuleDependency(List<ModuleIdentifier> dependencies, ElementNode parentNode, ModuleDependency dep) throws IOException, XMLStreamException {
        ModuleIdentifier moduleId = dep.getModuleId();
        ElementNode moduleNode = new ElementNode(parentNode, "module");
        moduleNode.addAttribute("name", new AttributeValue(moduleId.toString()));
        if (dep.isOptional()) {
            moduleNode.addAttribute("optional", new AttributeValue("true"));
        }

        if (dependencies.contains(moduleId)) {
            moduleNode.addAttribute("defined", new AttributeValue("true"));
            parentNode.addChild(moduleNode);
        } else {
            parentNode.addChild(moduleNode);

            String path = moduleId.getName().replace('.', '/') + File.separator + moduleId.getSlot();
            File moduleFile = new File(resourcesDir + File.separator + "modules" + File.separator + path + File.separator + "module.xml");
            if (moduleFile.exists() || !dep.isOptional()) {
                dependencies.add(moduleId);

                ModuleParser moduleParser = new ModuleParser(moduleFile);
                moduleParser.parse();

                List<ModuleDependency> moduledeps = moduleParser.getDependencies();
                for (ModuleDependency aux : moduledeps) {
                    processModuleDependency(dependencies, moduleNode, aux);
                }
            }
        }
    }
}

@@ -6152,38 +6152,27 @@
 '.', '/') + 
-File.separator
+'/'
  + moduleId.
@@ -6216,38 +6216,27 @@
 ntln(path + 
-File.separator
+'/'
  + %22**%22);%0A  
@@ -7637,30 +7637,19 @@
  '/') + 
-File.separator
+'/'
  + modul

Fix tests broken on Windows