import org.elasticsearch.gradle.internal.test.RestIntegTestTask
import org.elasticsearch.gradle.testclusters.TestClusterValueSource
import org.elasticsearch.gradle.testclusters.TestClustersPlugin
import org.elasticsearch.gradle.testclusters.TestClustersRegistry
import org.elasticsearch.gradle.util.GradleUtils

apply plugin: 'elasticsearch.internal-test-artifact'

dependencies {
  testImplementation project(':x-pack:plugin:core')
  testImplementation(project(':x-pack:plugin:sql:qa:jdbc'))
  // We use the shadowjar for testing since that's the actual artifact we deliver to users
  testCompileOnly project(path: xpackModule('sql:jdbc'), configuration: 'shadow')
}

Project mainProject = project


subprojects {
  def clusterPath = getPath()

  // Use tests from the root security qa project in subprojects
  configurations.create('testArtifacts').transitive = false

  dependencies {
    javaRestTestImplementation project(":x-pack:plugin:core")
    testArtifacts testArtifact(project(mainProject.path))

  }

  testClusters.configureEach {
    testDistribution = 'DEFAULT'
    // Setup auditing so we can use it in some tests
    setting 'xpack.security.audit.enabled', 'true'
    setting 'xpack.security.enabled', 'true'
    setting 'xpack.license.self_generated.type', 'trial'
    // Setup roles used by tests
    rolesFile mainProject.file('roles.yml')
    /* Setup the one admin user that we run the tests as.
     * Tests use "run as" to get different users. */
    user username: "test_admin", password: "x-pack-test-password"
  }

  File testArtifactsDir = project.file("$buildDir/testArtifacts")
  TaskProvider copyTestClasses = tasks.register("copyTestClasses", Copy) {
    dependsOn configurations.testArtifacts
    from { zipTree(configurations.testArtifacts.singleFile) }
    into testArtifactsDir
  }


  tasks.withType(RestIntegTestTask).configureEach {
    def taskName = name
    dependsOn copyTestClasses
    classpath += configurations.testArtifacts
    testClassesDirs = project.files(testArtifactsDir)
    def clusterInfo = getClusterInfo(taskName);
    nonInputProperties.systemProperty 'tests.audit.logfile', clusterInfo.map { it.auditLogs.get(0) }
    nonInputProperties.systemProperty 'tests.audit.yesterday.logfile',
      clusterInfo.map { it.auditLogs.get(0).getParentFile().toString() + "/javaRestTest_audit-${new Date().format('yyyy-MM-dd')}-1.json" }
  }
}
