/**
   * Executes the requested Grails target. The "targetName" must match a known Grails script
   * provided by grails-scripts.
   *
   * @param targetName The name of the Grails target to execute.
   * @param args String of arguments to be passed to the executed Grails target.
   * @throws MojoExecutionException if an error occurs while attempting to execute the target.
   */
  protected void runGrails(final String targetName, String args) throws MojoExecutionException {
    if (((lastArgs != null && lastArgs.equals(args)) || (lastArgs == null && args == null))
        && lastTargetName != null
        && lastTargetName.equals(targetName)) return;

    lastArgs = args;
    lastTargetName = targetName;

    if (!alreadyLoaderClasspathForArtifact()) doOncePerArtifact();
    else if (targetName.equals("War")) resolveClasspath(); // we have to get rid of the test rubbish

    getLog()
        .info(
            "Grails target: "
                + targetName
                + " raw args:"
                + args
                + " (pom says Grails Version is "
                + grailsVersion
                + ")");

    InputStream currentIn = System.in;
    PrintStream currentOutput = System.out;

    try {
      RootLoader rootLoader = new RootLoader(addBinaryPluginWorkaround(classpath));

      // see if log4j is there and if so, initialize it
      try {
        Class cls = rootLoader.loadClass("org.springframework.util.Log4jConfigurer");
        invokeStaticMethod(
            cls, "initLogging", new Object[] {"classpath:grails-maven/log4j.properties"});
      } catch (Exception ex) {
        getLog().info("No log4j available, good!");
      }

      try {
        final DecentGrailsLauncher launcher =
            new DecentGrailsLauncher(rootLoader, grailsHomePath, basedir.getAbsolutePath());
        launcher.setPlainOutput(true);

        /**
         * this collects the different dependency levels (compile, runtime, test) and puts them into
         * the correct arrays to pass through to the Grails script launcher. If using Maven, you
         * should *never* see an Ivy message and if you do, immediately stop your build, figure out
         * the incorrect dependency, delete the ~/.ivy2 directory and try again.
         */
        Field settingsField = launcher.getClass().getDeclaredField("settings");
        settingsField.setAccessible(true);

        configureBuildSettings(
            launcher,
            resolvedArtifacts,
            settingsField,
            rootLoader.loadClass("grails.util.BuildSettings"),
            args);

        syncAppVersion();

        installGrailsPlugins(
            pluginDirectories,
            launcher,
            settingsField,
            rootLoader.loadClass("grails.util.AbstractBuildSettings"));

        // If the command is running in non-interactive mode, we
        // need to pass on the relevant argument.
        if (this.nonInteractive) {
          args = (args != null) ? "--non-interactive " + args : "--non-interactive ";
        }

        // consuming the standard output after execution via Maven.
        args = (args != null) ? "--plain-output " + args : "--plain-output";
        args = (args != null) ? "--stacktrace " + args : "--stacktrace";
        args = (args != null) ? "--verboseCompile " + args : "--verboseCompile";

        if (env == null) System.clearProperty("grails.env");
        else System.setProperty("grails.env", env);

        getLog()
            .info(
                "grails -Dgrails.env="
                    + (env == null ? "dev" : env)
                    + " "
                    + targetName.toLowerCase()
                    + " "
                    + args);
        int retval;

        if ("true".equals(System.getProperty("print.grails.settings"))
            || "ideaprintprojectsettings".equalsIgnoreCase(targetName)) {
          printIntellijIDEASettings(launcher, settingsField, pluginArtifacts);
        } else {

          if ("interactive".equals(targetName)) retval = launcher.launch("", "", env);
          else retval = launcher.launch(targetName, args, env);

          if (retval != 0) {
            throw new MojoExecutionException("Grails returned non-zero value: " + retval);
          }
        }
      } catch (final MojoExecutionException ex) {
        // Simply rethrow it.
        throw ex;
      } catch (final Exception ex) {
        getLog().error(ex);

        throw new MojoExecutionException("Unable to start Grails", ex);
      }

      rootLoader = null;
    } catch (MalformedURLException mfe) {
      throw new MojoExecutionException("Unable to start Grails", mfe);
    } finally {
      System.setIn(currentIn);
      System.setOut(currentOutput);
    }

    System.gc(); // try and help with memory issues
  }
  /**
   * Configures the launcher for execution.
   *
   * @param launcher The {@code GrailsLauncher} instance to be configured.
   */
  @SuppressWarnings("unchecked")
  private Set<Artifact> configureBuildSettings(
      final DecentGrailsLauncher launcher,
      Set<Artifact> resolvedArtifacts,
      Field settingsField,
      Class clazz,
      String args)
      throws ProjectBuildingException, MojoExecutionException {
    final String targetDir = this.project.getBuild().getDirectory();
    launcher.setDependenciesExternallyConfigured(true);

    // allow plugins that are being developed with fake api implementations to include the test
    // artifacts in the runtime
    if ((args != null && args.contains("--run-with-test-dependencies"))
        || runWithTestDependencies) {
      getLog().warn("grails-maven: Running with test dependencies");
      List<File> artifacts =
          artifactsToFiles(filterArtifacts(resolvedArtifacts, "compile", "runtime", "test"));
      launcher.setCompileDependencies(artifacts);
      launcher.setRuntimeDependencies(artifacts);
      launcher.setTestDependencies(artifacts);
    } else {
      // getCompileArtifacts, getRuntimeArtifacts and getTestArticats on the project are not
      // reliable
      logDependencies = "true".equals(System.getProperty("grails.maven.dependencies.compile"));
      launcher.setCompileDependencies(
          artifactsToFiles(filterArtifacts(resolvedArtifacts, "compile")));
      logDependencies = "true".equals(System.getProperty("grails.maven.dependencies.runtime"));
      launcher.setRuntimeDependencies(
          artifactsToFiles(filterArtifacts(resolvedArtifacts, "compile", "runtime")));
      logDependencies = "true".equals(System.getProperty("grails.maven.dependencies.test"));
      launcher.setTestDependencies(
          artifactsToFiles(filterArtifacts(resolvedArtifacts, "compile", "runtime", "test")));
      logDependencies = false;
    }

    launcher.setProjectWorkDir(new File(targetDir));
    launcher.setClassesDir(new File(targetDir, "classes"));
    launcher.setTestClassesDir(new File(targetDir, "test-classes"));
    launcher.setResourcesDir(new File(targetDir, "resources"));
    launcher.setProjectPluginsDir(this.pluginsDir);

    logDependencies = "true".equals(System.getProperty("grails.maven.dependencies.build"));
    List<File> files = artifactsToFiles(resolvedArtifacts);
    logDependencies = false;

    launcher.setBuildDependencies(files);

    Object settings = null;
    try {
      settings = settingsField.get(launcher);

      Field f = settings.getClass().getDeclaredField("defaultPluginSet");
      f.setAccessible(true);
      f.set(settings, new HashSet());
      f = settings.getClass().getDeclaredField("defaultPluginMap");
      f.setAccessible(true);
      f.set(settings, new LinkedHashMap());
      f = settings.getClass().getDeclaredField("enableResolve");
      f.setAccessible(true);
      f.set(settings, false);

    } catch (Exception e) {
      getLog().error("Unable to set default plugin set to empty ", e);
    }

    return resolvedArtifacts;
  }