/*
 * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code 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 General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

import java.io.*;
import java.module.*;
import java.util.*;
import sun.module.JamUtils;
import sun.module.tools.JRepo;

/**
 * @test
 * @compile -XDignore.symbol.file
 *    RunMTest.java
 *    classp/MainX.java
 *    JRepoValidateTest.java
 * @run main/othervm
 *    -DTestDescriptionFactory.classname=JRepoValidateTest$MyFactory
 *    JRepoValidateTest
 */
public class JRepoValidateTest {
    private static final boolean debug = Boolean.getBoolean("module.tools.debug");

    private static final ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
    private static final PrintStream outStream = new PrintStream(outBytes);
    private static final ByteArrayOutputStream errBytes = new ByteArrayOutputStream();
    private static final PrintStream errStream = new PrintStream(errBytes);

    private static final String[] tests = {
        "basic/import.mtest",
    };


    public static void realMain(String args[]) throws Throwable {
        RunMTest.main(tests);
    }

    /** Return an array of Strings from the given String. */
    static String[] getArgs(String s) {
        List<String> args = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(s);
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (debug) System.err.println("adding arg " + token);
            args.add(token);
        }
        if (debug) System.err.println("args length is " + args.size());
        return args.toArray(new String[0]);
    }

    public static class MyFactory extends RunMTest.TestDescriptionFactory {

        protected RunMTest.TestDescription doCreate(String name) {
            return new MyTestDescription(name);
        }
    }

    public static class MyTestDescription extends RunMTest.TestDescription {
        MyTestDescription(String name) {
            super(name);
        }

        protected void runTest(RunMTest mTest) throws Exception {
            if (name.equals("m2")) {
                // Only run this for m1.
                return;
            }

            Repository parent = sun.module.repository.RepositoryConfig.getApplicationRepository();
            Repository repository = Modules.newLocalRepository(
                mTest.getName(), mTest.outputDirectory, null, parent);

            ModuleArchiveInfo[] maiList = new ModuleArchiveInfo[2];

            for (ModuleArchiveInfo mai : repository.list()) {
                if (mai.getName().equals("m1")) {
                    maiList[0] = mai;
                } else if (mai.getName().equals("m2")) {
                    maiList[1] = mai;
                }
            }

            JRepo jr = new JRepo(outStream, errStream, null);

            // Check deep validation on module m1 which imports m2
            try {
                check(jr.run(getArgs(
                                 "validate -d -v -r "
                                 + mTest.outputDirectory.getAbsolutePath() + " "
                                 + maiList[0].getName())));
                checkOutput("passed deep validation", outBytes);
            } catch (Throwable t) {
                unexpected(t);
            }

            // Check shallow validation on module m1 which imports m2
            try {
                check(jr.run(getArgs(
                                 "validate -v -r "
                                 + mTest.outputDirectory.getAbsolutePath() + " "
                                 + maiList[0].getName())));
                checkOutput("passed shallow validation", outBytes);
            } catch (Throwable t) {
                unexpected(t);
            }

            // Install m1 into a new repository, and validate, expecting failure
            File repoDir = new File(mTest.outputDirectory, "validateA");
            check(JamUtils.recursiveDelete(repoDir));
            check(repoDir.mkdirs());
            repository = Modules.newLocalRepository(
                mTest.getName() + "validateA", repoDir, null, parent);
            check(repository.install(
                      new File(maiList[0].getFileName()).toURI()) != null);
            try {
                check(false == jr.run(getArgs(
                                          "validate -d -r "
                                          + repoDir.getAbsolutePath() + " "
                                          + maiList[0].getName())));
                checkOutput("no module definition in the repository can satisfy the import dependency ModuleDependency", errBytes);
            } catch (Throwable t) {
                unexpected(t);
            }
        }

        static void checkOutput(String expected, ByteArrayOutputStream baos) {
            String actual = baos.toString();
            if (!check(actual.contains(expected))) {
                System.err.println(
                    "Got\n'" + actual + "'\nbut expected\n'" + expected + "'");
            }
            // Reset both streams after checking either one.
            outBytes.reset();
            errBytes.reset();
        }
    }

    //--------------------- Infrastructure ---------------------------
    static volatile int passed = 0, failed = 0;
    static boolean pass() {passed++; return true;}
    static boolean fail() {failed++; Thread.dumpStack(); return false;}
    static boolean fail(String msg) {System.err.println(msg); return fail();}
    static void unexpected(Throwable t) {failed++; t.printStackTrace();}
    static boolean check(boolean cond) {if (cond) pass(); else fail(); return cond;}
    static boolean equal(Object x, Object y) {
        if (x == null ? y == null : x.equals(y)) return pass();
        else return fail(x + " not equal to " + y);}
    public static void main(String[] args) throws Throwable {
        try {realMain(args);} catch (Throwable t) {unexpected(t);}
        System.out.println("\nPassed = " + passed + " failed = " + failed);
        if (failed > 0) throw new AssertionError("Some tests failed");}
}
