/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

import org.elasticsearch.gradle.VersionProperties
import org.elasticsearch.gradle.testclusters.StandaloneRestIntegTestTask

apply plugin: 'elasticsearch.legacy-java-rest-test'
apply plugin: 'elasticsearch.bwc-test'

dependencies {
  javaRestTestImplementation project(':x-pack:qa')
}

// Only run tests for 7.9+, since the node.roles setting was introduced in 7.9.0
buildParams.bwcVersions.withWireCompatible(v -> v.onOrAfter("7.9.0") &&
        v != VersionProperties.getElasticsearchVersion()) { bwcVersion, baseName ->

  def baseCluster = testClusters.register(baseName) {
    versions = [bwcVersion.toString(), project.version]
    numberOfNodes = 3
    testDistribution = 'DEFAULT'
    setting 'xpack.security.enabled', 'false'
    setting 'xpack.watcher.enabled', 'false'
    setting 'xpack.ml.enabled', 'false'
    setting 'xpack.license.self_generated.type', 'trial'
    nodes."${baseName}-0".setting 'node.roles', '["master"]'
    // data_* roles were introduced in 7.10.0, so use 'data' for older versions
    if (bwcVersion.before('7.10.0')) {
      nodes."${baseName}-1".setting 'node.roles', '["data"]'
    } else {
      nodes."${baseName}-1".setting 'node.roles', '["data_content", "data_hot"]'
    }
    nodes."${baseName}-2".setting 'node.roles', '["master"]'
  }

  tasks.register("${baseName}#mixedClusterTest", StandaloneRestIntegTestTask) {
    useCluster baseCluster
    mustRunAfter("precommit")
    def beforeEndpoints = getClusterInfo(baseName).map { it.allHttpSocketURI.join(",") }
    doFirst {
      // Getting the endpoints causes a wait for the cluster
      println "Endpoints are: ${-> beforeEndpoints.get()}"
      getRegistry().get().nextNodeToNextVersion(baseCluster)
    }
    nonInputProperties.systemProperty('tests.rest.cluster', getClusterInfo(baseName).map { it.allHttpSocketURI.join(",") })
    nonInputProperties.systemProperty('tests.clustername', baseName)
    onlyIf("BWC tests disabled") { project.bwc_tests_enabled }
  }

  tasks.register(bwcTaskName(bwcVersion)) {
    dependsOn "${baseName}#mixedClusterTest"
  }
}

tasks.withType(Test).configureEach {
  classpath = sourceSets.javaRestTest.runtimeClasspath
  testClassesDirs = sourceSets.javaRestTest.output.classesDirs
  // Security is explicitly disabled, do not run tests in FIPS mode
  buildParams.withFipsEnabledOnly(it)
}
