/** Returns a list of all the executable Gant scripts available to this application. */
  public List<File> getAvailableScripts() {
    List<File> scripts = new ArrayList<File>();
    if (settings.getGrailsHome() != null) {
      addCommandScripts(new File(settings.getGrailsHome(), "scripts"), scripts);
      addCommandScripts(
          new File(settings.getGrailsHome(), "grails-scripts/src/main/scripts"), scripts);
    }
    addCommandScripts(new File(settings.getBaseDir(), "scripts"), scripts);
    addCommandScripts(new File(settings.getUserHome(), ".grails/scripts"), scripts);

    for (File dir : pluginPathSupport.listKnownPluginDirs()) {
      addPluginScripts(dir, scripts);
    }

    PathMatchingResourcePatternResolver resolver =
        new PathMatchingResourcePatternResolver(settings.getRootLoader());
    try {
      final Resource[] resources = resolver.getResources("classpath*:META-INF/scripts/*.groovy");
      for (Resource resource : resources) {
        scripts.add(resource.getFile());
      }
    } catch (IOException e) {
      // ignore
    }
    return scripts;
  }
  protected void initializeLogging() {
    if (settings.getGrailsHome() == null) {
      return;
    }

    try {
      Class<?> cls =
          Thread.currentThread()
              .getContextClassLoader()
              .loadClass("org.apache.log4j.PropertyConfigurator");
      Method configure = cls.getMethod("configure", URL.class);
      configure.setAccessible(true);
      File f =
          new File(settings.getGrailsHome() + "/grails-scripts/src/main/scripts/log4j.properties");
      if (f.exists()) {
        configure.invoke(cls, f.toURI().toURL());
      } else {
        f = new File(settings.getGrailsHome() + "/scripts/log4j.properties");
        configure.invoke(cls, f.toURI().toURL());
      }
    } catch (Throwable e) {
      console.verbose(
          "Log4j was not found on the classpath and will not be used for command line logging. Cause "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }
  }
  protected void initializeLogging() {
    if (settings.getGrailsHome() == null) {
      return;
    }

    try {
      org.springframework.util.Log4jConfigurer.initLogging(
          "file:" + settings.getGrailsHome() + "/scripts/log4j.properties");
    } catch (Throwable e) {
      console.verbose(
          "Log4j was not found on the classpath and will not be used for command line logging. Cause "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }
  }
  public BaseSettingsApi(
      BuildSettings settings, GrailsBuildEventListener buildEventListener, boolean interactive) {
    buildSettings = settings;
    buildProps = buildSettings.getConfig().toProperties();
    grailsHome = buildSettings.getGrailsHome();

    metadataFile = new File(buildSettings.getBaseDir(), "application.properties");

    metadata = metadataFile.exists() ? Metadata.getInstance(metadataFile) : Metadata.getCurrent();

    metadataFile = metadata.getMetadataFile();
    enableProfile = Boolean.valueOf(getPropertyValue("grails.script.profile", false).toString());
    pluginsHome = buildSettings.getProjectPluginsDir().getPath();
    pluginSettings = GrailsPluginUtils.getPluginBuildSettings(settings);
    grailsAppName = metadata.getApplicationName();
    isInteractive = interactive;

    // If no app name property (upgraded/new/edited project) default to basedir.
    if (grailsAppName == null) {
      grailsAppName = buildSettings.getBaseDir().getName();
    }

    if (grailsAppName.indexOf('/') > -1) {
      appClassName =
          grailsAppName.substring(grailsAppName.lastIndexOf('/'), grailsAppName.length());
    } else {
      appClassName = GrailsNameUtils.getClassNameRepresentation(grailsAppName);
    }
    configSlurper = buildSettings.createConfigSlurper();
    configSlurper.setEnvironment(buildSettings.getGrailsEnv());
    this.buildEventListener = buildEventListener;
  }
  /**
   * Evaluate the arguments to get the name of the script to execute, which environment to run it
   * in, and the arguments to pass to the script. This also evaluates arguments of the form
   * "-Dprop=value" and creates system properties from each one.
   *
   * @param args Command line arguments
   */
  public static void main(String[] args) {
    originalIn = System.in;
    originalOut = System.out;

    CommandLineParser parser = getCommandLineParser();

    GrailsConsole console = GrailsConsole.getInstance();

    CommandLine commandLine;
    try {
      if (args.length == 0) {
        commandLine = new DefaultCommandLine();
      } else {
        commandLine = parser.parseString(args[0]);
        if (commandLine.hasOption(CommandLine.NOANSI_ARGUMENT)) {
          console.setAnsiEnabled(false);
        }
      }
    } catch (ParseException e) {
      console.error("Error processing command line arguments: " + e.getMessage());
      System.exit(1);
      return;
    }

    String version = System.getProperty("grails.version");

    ScriptAndArgs script = processArgumentsAndReturnScriptName(commandLine);

    // Get hold of the GRAILS_HOME environment variable if it is available.
    String grailsHome = System.getProperty("grails.home");

    // Now we can pick up the Grails version from the Ant project properties.
    BuildSettings build = null;
    try {
      build = new BuildSettings(new File(grailsHome));
      build.setModified(commandLine.hasOption(CommandLine.REFRESH_DEPENDENCIES_ARGUMENT));
      build.setOffline(commandLine.hasOption(CommandLine.OFFLINE_ARGUMENT));
      if (build.getRootLoader() == null) {
        build.setRootLoader((URLClassLoader) GrailsScriptRunner.class.getClassLoader());
      }
    } catch (Exception e) {
      exitWithError(
          "An error occurred loading the grails-app/conf/BuildConfig.groovy file: "
              + e.getMessage(),
          null);
    }

    // Check that Grails' home actually exists.
    final File grailsHomeInSettings = build.getGrailsHome();
    if (grailsHomeInSettings == null || !grailsHomeInSettings.exists()) {
      exitWithError("Grails' installation directory not found: " + build.getGrailsHome(), null);
    }

    if (commandLine.hasOption(CommandLine.VERSION_ARGUMENT)) {
      console.log("Grails version: " + build.getGrailsVersion());
      System.exit(0);
    }

    if (commandLine.hasOption(CommandLine.HELP_ARGUMENT)) {
      console.log(parser.getHelpMessage());
      System.exit(0);
    }

    // If there aren't any arguments, then we don't have a command
    // to execute, so enter "interactive mode"
    boolean resolveDeps = commandLine.hasOption(CommandLine.REFRESH_DEPENDENCIES_ARGUMENT);
    if (resolveDeps) {
      if (commandLine.hasOption("include-source")) {
        build.setIncludeSource(true);
      }
      if (commandLine.hasOption("include-javadoc")) {
        build.setIncludeJavadoc(true);
      }
    }
    GrailsScriptRunner scriptRunner = new GrailsScriptRunner(build);
    scriptRunner.setInteractive(!commandLine.hasOption(CommandLine.NON_INTERACTIVE_ARGUMENT));
    if ("Interactive".equals(script.name)) {
      console.error(
          "The 'interactive' script is deprecated; to run in interactive mode just omit the script name");
      script.name = null;
    }
    if (script.name == null) {
      console.updateStatus(
          "Loading Grails " + (version != null ? version : build.getGrailsVersion()));

      build.loadConfig();
      if (resolveDeps) {
        ClasspathConfigurer.cleanResolveCache(build);
      }
      scriptRunner.initializeState();
      try {
        new InteractiveMode(build, scriptRunner).run();
      } catch (Throwable e) {
        console.error("Interactive mode exited with error: " + e.getMessage(), e);
      }
    } else {
      console.getCategory().push(script.inputName);
      console.verbose("Base Directory: " + build.getBaseDir().getPath());

      try {
        int exitCode = scriptRunner.executeCommand(commandLine, script.name, script.env);
        System.exit(exitCode);
      } catch (ScriptNotFoundException ex) {
        console.error("Script not found: " + ex.getScriptName());
      } catch (Throwable t) {
        String msg = "Error executing script " + script.name + ": " + t.getMessage();
        exitWithError(msg, t);
      }
    }
  }