/*
 * Copyright 2014 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
 *
 *      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.gradle.buildinit.plugins;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.logging.Logger;
import org.gradle.api.specs.Spec;
import org.gradle.buildinit.plugins.internal.modifiers.BuildInitDsl;
import org.gradle.buildinit.tasks.InitBuild;

import java.io.File;
import java.util.concurrent.Callable;

/**
 * The build init plugin.
 *
 * @see <a href="https://docs.gradle.org/current/userguide/build_init_plugin.html">Build Init plugin reference</a>
 */
public class BuildInitPlugin implements Plugin<Project> {

    @Override
    public void apply(Project project) {
        if (project.getParent() == null) {
            project.getTasks().register("init", InitBuild.class, initBuild -> {
                initBuild.setGroup("Build Setup");
                initBuild.setDescription("Initializes a new Gradle build.");

                File buildFile = project.getBuildFile();
                boolean hasSubProjects = !project.getSubprojects().isEmpty();
                File userHome = project.getGradle().getGradleUserHomeDir();

                initBuild.onlyIf(new InitBuildOnlyIfSpec(buildFile, project.getLayout(), hasSubProjects, userHome, initBuild.getLogger()));
                initBuild.dependsOn(new InitBuildDependsOnCallable(buildFile, project.getLayout(), hasSubProjects, userHome));

                ProjectInternal.DetachedResolver detachedResolver = ((ProjectInternal) project).newDetachedResolver();
                initBuild.getProjectLayoutRegistry().getBuildConverter().configureClasspath(detachedResolver, project.getObjects());
            });
        }
    }

    private static class InitBuildOnlyIfSpec implements Spec<Task> {

        private final File buildFile;
        private final ProjectLayout layout;
        private final boolean hasSubProjects;
        private final File userHome;
        private final Logger logger;

        private InitBuildOnlyIfSpec(File buildFile, ProjectLayout layout, boolean hasSubProjects, File userHome, Logger logger) {
            this.buildFile = buildFile;
            this.layout = layout;
            this.hasSubProjects = hasSubProjects;
            this.userHome = userHome;
            this.logger = logger;
        }

        @Override
        public boolean isSatisfiedBy(Task element) {
            String skippedMsg = reasonToSkip(buildFile, layout, hasSubProjects, userHome);
            if (skippedMsg != null) {
                logger.warn(skippedMsg);
                return false;
            }
            return true;
        }
    }

    private static class InitBuildDependsOnCallable implements Callable<String> {

        private final File buildFile;
        private final ProjectLayout layout;
        private final boolean hasSubProjects;
        private final File userHome;

        private InitBuildDependsOnCallable(File buildFile, ProjectLayout layout, boolean hasSubProjects, File userHome) {
            this.buildFile = buildFile;
            this.layout = layout;
            this.hasSubProjects = hasSubProjects;
            this.userHome = userHome;
        }

        @Override
        public String call() {
            if (reasonToSkip(buildFile, layout, hasSubProjects, userHome) == null) {
                return "wrapper";
            } else {
                return null;
            }
        }
    }

    private static String reasonToSkip(File buildFile, ProjectLayout layout, boolean hasSubProjects, File userHome) {
        if (layout.getProjectDirectory().dir(".gradle").getAsFile().equals(userHome)) {
            return "Gradle user home directory (" + userHome + ") overlaps with the project cache directory";
        }

        for (BuildInitDsl dsl : BuildInitDsl.values()) {
            String buildFileName = dsl.fileNameFor("build");
            if (layout.getProjectDirectory().file(buildFileName).getAsFile().exists()) {
                return "The build file '" + buildFileName + "' already exists. Skipping build initialization.";
            }
            String settingsFileName = dsl.fileNameFor("settings");
            if (layout.getProjectDirectory().file(settingsFileName).getAsFile().exists()) {
                return "The settings file '" + settingsFileName + "' already exists. Skipping build initialization.";
            }
        }

        if (buildFile != null && buildFile.exists()) {
            return "The build file '" + buildFile.getName() + "' already exists. Skipping build initialization.";
        }

        if (hasSubProjects) {
            return "This Gradle project appears to be part of an existing multi-project Gradle build. Skipping build initialization.";
        }

        return null;
    }
}

@@ -1022,16 +1022,96 @@
 tBuild;%0A
+import org.gradle.cache.internal.CacheScopeMapping;%0A%0Aimport javax.inject.Inject;
 %0Aimport 
@@ -1370,24 +1370,151 @@
 Project%3E %7B%0A%0A
+    @Inject%0A    protected CacheScopeMapping getCacheScopeMapping() %7B%0A        throw new UnsupportedOperationException();%0A    %7D%0A%0A
     @Overrid
@@ -2018,16 +2018,101 @@
 meDir();
+%0A                File projectRoot = getCacheScopeMapping().getRootDirectory(project);
 %0A%0A      
@@ -2219,16 +2219,29 @@
 serHome,
+ projectRoot,
  initBui
@@ -2381,16 +2381,29 @@
 userHome
+, projectRoot
 ));%0A%0A   
@@ -2911,32 +2911,72 @@
  File userHome;%0A
+        private final File projectRoot;%0A
         private 
@@ -3109,16 +3109,34 @@
 serHome,
+ File projectRoot,
  Logger 
@@ -3299,32 +3299,76 @@
 ome = userHome;%0A
+            this.projectRoot = projectRoot;%0A
             this
@@ -3555,16 +3555,29 @@
 userHome
+, projectRoot
 );%0A     
@@ -3983,16 +3983,56 @@
 serHome;
+%0A        private final File projectRoot;
 %0A%0A      
@@ -4135,32 +4135,50 @@
 s, File userHome
+, File projectRoot
 ) %7B%0A            
@@ -4319,32 +4319,76 @@
 ome = userHome;%0A
+            this.projectRoot = projectRoot;%0A
         %7D%0A%0A     
@@ -4503,16 +4503,29 @@
 userHome
+, projectRoot
 ) == nul
@@ -4762,79 +4762,53 @@
 Home
-) %7B%0A        if (layout.getProjectDirectory().dir(%22.gradle%22).getAsFile()
+, File projectRoot) %7B%0A        if (projectRoot
 .equ

Change how the project root is obtained