/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

allprojects {
  apply plugin: 'base'

  group "org.apache"

  // def lucenePrereleaseBuild = '9'

  // Repositories to fetch dependencies from.
  repositories {
    mavenCentral()
    // Note: The maven repository below is temorary and will be removed eventually.
    maven {
      name "SearchScale"
      url "https://maven.searchscale.com/snapshots"
    }
    /* Reenable this if we need it again in future
    maven {
      name "LucenePrerelease${lucenePrereleaseBuild}"
      url "https://nightlies.apache.org/solr/lucene-prereleases/${lucenePrereleaseBuild}/"
    }
    */
  }

  // Artifacts will have names after full gradle project path
  // so :solr:core will have solr-core.jar, etc.
  project.archivesBaseName = project.path
          .replaceAll("^:", "")
          .replace(':', '-')
          .replace("-modules-", "-")

  project.ext {
    // Utility method to support passing overrides via -P or -D.
    propertyOrDefault = { propName, defValue ->
      def result
      if (project.hasProperty(propName)) {
        result = project.getProperty(propName)
      } else if (System.properties.containsKey(propName)) {
        result = System.properties.get(propName)
      } else if (defValue instanceof Closure) {
        result = defValue.call()
      } else {
        result = defValue
      }
      return result
    }

    // System environment variable or default.
    envOrDefault = { envName, defValue ->
      return Objects.requireNonNullElse(System.getenv(envName), defValue);
    }

    // Either a project, system property, environment variable or default value.
    propertyOrEnvOrDefault = { propName, envName, defValue ->
      return propertyOrDefault(propName, envOrDefault(envName, defValue));
    }

    // Locate script-relative resource folder. This is context-sensitive so pass
    // the right buildscript (top-level).
    scriptResources = { buildscript ->
      return file(buildscript.sourceFile.absolutePath.replaceAll('.gradle$', ""))
    }

    failOrWarn = { propName, message, errors ->
      if (errors) {
        def shouldFail = Boolean.valueOf(propertyOrDefault(propName, true))
        def msg = message + (shouldFail ? " (skip with -P${propName}=false)" : "") + ":\n${errors.join("\n")}"

        if (shouldFail) {
          throw new GradleException(msg)
        } else {
          logger.warn("NOTE: ${msg}")
        }
      }
    }

    // Utility function similar to project.exec but not emitting
    // any output unless an error code is returned from the executed command.
    quietExec = { closure ->
      // Resolve any properties against the provided closure.
      resolveStrategy = Closure.DELEGATE_ONLY
      delegate = closure.delegate

      File outputFile = File.createTempFile("exec-output-", ".txt", getTemporaryDir())
      ExecResult result
      boolean saveIgnoreExitValue
      ExecSpec saveExecSpec

      outputFile.withOutputStream { output ->
        // we want to capture both stdout and stderr to the same
        // stream but gradle attempts to close these separately
        // (it has two independent pumping threads) and it can happen
        // that one still tries to write something when the other closed
        // the underlying output stream.
        def wrapped = new java.io.FilterOutputStream(output) {
          public void close() {
            // no-op. we close this stream manually.
          }
        }

        result = project.exec { ExecSpec execSpec ->
          project.configure(execSpec, closure)

          saveIgnoreExitValue = execSpec.ignoreExitValue
          saveExecSpec = execSpec

          standardOutput = wrapped
          errorOutput = wrapped
          ignoreExitValue true
        }
      }

      if (result.getExitValue() != 0) {
        // Pipe the output to console. Intentionally skips any encoding conversion
        // and pumps raw bytes.
        logger.error(new String(outputFile.bytes))

        if (!saveIgnoreExitValue) {
          result.rethrowFailure()
          throw new GradleException("The executed process ${saveExecSpec.executable} " +
              "returned an odd status " +
              "code: ${result.exitValue}, " +
              "output at: ${outputFile} (and logged above).")
        }
      }

      return result
    }

    // Convert a list of strings, tasks and task providers into resolved tasks or task providers.
    resolveTaskRefs = { List<Object> refs ->
      def resolved = refs.collect {
        if (it instanceof Task) return it
        if (it instanceof TaskProvider) return it
        if (it instanceof String) return project.tasks.named((String) it)
        throw new GradleException("Can't resolve task: ${it}")
      }
      return resolved
    }

    // Forces sequential ordering of a list of tasks (via mustRunAfter).
    // This method should not be required in 99% of cases, consider regular dependsOn links.
    // This method does NOT imply any ordering between dependencies of task on the input
    // list - the execution of these may still be unordered.
    mustRunInOrder = { List<Object> taskList ->
      project.afterEvaluate {
        def resolved = resolveTaskRefs(taskList)

        // Enforce sequential ordering between tasks (this does NOT apply to their dependencies!)
        for (int i = 1; i < resolved.size(); i++) {
          resolved[i].configure {
            logger.info("Scheduling " + resolved[i].name + " to run after " + resolved[i - 1].name)
            mustRunAfter resolved[i - 1]
          }
        }
      }
      return taskList
    }

    // detect if we run in CI environment by looking at existence of env vars:
    // "CI": Github (https://docs.github.com/en/actions/learn-github-actions/environment-variables)
    // anything starting with "JENKINS_" or "HUDSON_": Jenkins/Hudson (https://jenkins.thetaphi.de/env-vars.html/)
    isCIBuild = System.getenv().keySet().any { it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/ }

    // Assign different java version for client-side modules 'api' and 'solrj*'
    var isSolrJ = project.name.matches("^(solrj.*|api)\$")
    minJavaVersion = isSolrJ ? rootProject.minJavaVersionSolrJ : rootProject.minJavaVersionDefault
    minJavaTestVersion = rootProject.minJavaVersionDefault
  }
}
