apply plugin: 'java'
apply plugin: 'com.gradleup.shadow'
apply plugin: 'io.opentelemetry.instrumentation.muzzle-generation'
apply plugin: 'io.opentelemetry.instrumentation.muzzle-check'

apply from: "$rootDir/gradle/shadow.gradle"

def relocatePackages = ext.relocatePackages

configurations {
  testInstrumentation
  testAgent
}

dependencies {
  compileOnly("io.opentelemetry:opentelemetry-sdk")
  compileOnly("io.opentelemetry.instrumentation:opentelemetry-instrumentation-api")
  compileOnly("io.opentelemetry.javaagent:opentelemetry-javaagent-extension-api")

  annotationProcessor deps.autoservice
  compileOnly deps.autoservice

  // the javaagent that is going to be used when running instrumentation unit tests
  testAgent(project(path: ":testing:agent-for-testing", configuration: "shadow"))
  // test dependencies
  testImplementation("io.opentelemetry.javaagent:opentelemetry-testing-common")
  testImplementation("io.opentelemetry:opentelemetry-sdk-testing")
  testImplementation("org.assertj:assertj-core:3.27.3")

  add("codegen", "io.opentelemetry.javaagent:opentelemetry-javaagent-tooling:${versions.opentelemetryJavaagentAlpha}")
  add("muzzleBootstrap", "io.opentelemetry.instrumentation:opentelemetry-instrumentation-annotations-support:${versions.opentelemetryJavaagentAlpha}")
  add("muzzleTooling", "io.opentelemetry.javaagent:opentelemetry-javaagent-extension-api:${versions.opentelemetryJavaagentAlpha}")
  add("muzzleTooling", "io.opentelemetry.javaagent:opentelemetry-javaagent-tooling:${versions.opentelemetryJavaagentAlpha}")
}

shadowJar {
  configurations = [project.configurations.runtimeClasspath, project.configurations.testInstrumentation]
  mergeServiceFiles()

  archiveFileName = 'agent-testing.jar'

  relocatePackages(it)
}

tasks.withType(Test).configureEach {
  inputs.file(shadowJar.archiveFile)

  jvmArgs "-Dotel.javaagent.debug=true"
  jvmArgs "-javaagent:${configurations.testAgent.files.first().absolutePath}"
  jvmArgs "-Dotel.javaagent.experimental.initializer.jar=${shadowJar.archiveFile.get().asFile.absolutePath}"
  jvmArgs "-Dotel.javaagent.testing.additional-library-ignores.enabled=false"
  jvmArgs "-Dotel.javaagent.testing.fail-on-context-leak=true"
  // prevent sporadic gradle deadlocks, see SafeLogger for more details
  jvmArgs "-Dotel.javaagent.testing.transform-safe-logging.enabled=true"

  dependsOn shadowJar
  dependsOn configurations.testAgent.buildDependencies

  // The sources are packaged into the testing jar so we need to make sure to exclude from the test
  // classpath, which automatically inherits them, to ensure our shaded versions are used.
  classpath = classpath.filter {
    if (it == file(layout.buildDirectory.dir("resources/main")) || it == file(layout.buildDirectory.dir("classes/java/main"))) {
      return false
    }
    return true
  }
}
