/*
 * 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", the "GNU Affero General Public License v3.0 only", and the "Server Side
 * Public License v 1"; you may not use this file except in compliance with, at
 * your election, the "Elastic License 2.0", the "GNU Affero General Public
 * License v3.0 only", or the "Server Side Public License, v 1".
 */

import org.elasticsearch.gradle.Version
import org.elasticsearch.gradle.internal.ElasticsearchTestBasePlugin
import org.elasticsearch.gradle.internal.test.rest.InternalJavaRestTestPlugin
import org.elasticsearch.gradle.testclusters.StandaloneRestIntegTestTask

ext.bwcTaskName = { Version version ->
  return "v${version}#bwcTest"
}

def bwcTestSnapshots = tasks.register("bwcTestSnapshots") {
  if (project.bwc_tests_enabled) {
    dependsOn tasks.matching { task -> buildParams.bwcVersions.unreleased.any { version -> bwcTaskName(version) == task.name } }
  }
}

tasks.register("bwcTest") {
  description = 'Runs backwards compatibility tests.'
  group = 'verification'

  if (project.bwc_tests_enabled) {
    dependsOn tasks.matching { it.name ==~ /v[0-9\.]+#bwcTest/ }
  }
}

plugins.withType(ElasticsearchTestBasePlugin) {
  tasks.withType(Test).matching { it.name ==~ /v[0-9\.]+#.*/ }.configureEach {
    boolean bwcEnabled = project.bwc_tests_enabled
    onlyIf("BWC tests enabled") { bwcEnabled }
    nonInputProperties.systemProperty 'tests.bwc', 'true'
  }
}

plugins.withType(InternalJavaRestTestPlugin) {
  tasks.named("javaRestTest") {
    enabled = false
  }

  tasks.withType(StandaloneRestIntegTestTask).configureEach {
    testClassesDirs = sourceSets.javaRestTest.output.classesDirs
    classpath = sourceSets.javaRestTest.runtimeClasspath
    usesDefaultDistribution("BWC tests require full distribution for now")
  }
}

tasks.matching { it.name.equals("check") }.configureEach { dependsOn(bwcTestSnapshots) }
tasks.matching { it.name.equals("test") }.configureEach { enabled = false }
