// common gradle file for instrumentation
import io.opentelemetry.instrumentation.gradle.bytebuddy.ByteBuddyPluginConfigurator

apply plugin: 'net.bytebuddy.byte-buddy'
apply plugin: 'muzzle'
apply plugin: 'com.github.johnrengelman.shadow'

ext {
  packageInAgentBundle = true
  mavenGroupId = 'io.opentelemetry.javaagent.instrumentation'
  // Shadow is only for testing, not publishing.
  noShadowPublish = true
}

apply from: "$rootDir/gradle/java.gradle"
if (project.ext.find("skipPublish") != true) {
  apply from: "$rootDir/gradle/publish.gradle"
}

apply from: "$rootDir/gradle/instrumentation-common.gradle"

if (projectDir.name == 'javaagent') {
  archivesBaseName = projectDir.parentFile.name
}

configurations {
  toolingRuntime {
    canBeConsumed = false
    canBeResolved = true
  }

  bootstrapRuntime {
    canBeConsumed = false
    canBeResolved = true
  }
}

afterEvaluate {
  dependencies {
    compileOnly project(':instrumentation-api')
    compileOnly project(':javaagent-api')
    compileOnly project(':javaagent-bootstrap')
    // Apply common dependencies for instrumentation.
    compileOnly(project(':javaagent-tooling')) {
      // OpenTelemetry SDK is not needed for compilation
      exclude group: 'io.opentelemetry', module: 'opentelemetry-sdk'
    }
    compileOnly deps.bytebuddy
    annotationProcessor deps.autoservice
    compileOnly deps.autoservice
    compileOnly deps.slf4j

    testImplementation deps.opentelemetryApi

    testImplementation project(':testing-common')
    testAnnotationProcessor deps.autoservice
    testCompileOnly deps.autoservice

    testImplementation deps.testcontainers

    toolingRuntime(project(path: ":javaagent-tooling", configuration: 'instrumentationMuzzle'))

    bootstrapRuntime(project(path: ":javaagent-bootstrap", configuration: 'instrumentationMuzzle'))
  }

  def pluginName = 'io.opentelemetry.javaagent.tooling.muzzle.collector.MuzzleCodeGenerationPlugin'
  new ByteBuddyPluginConfigurator(project, sourceSets.main, pluginName,
    configurations.toolingRuntime + configurations.runtimeClasspath
  ).configure()
}

configurations {
  testInstrumentation
}

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

  archiveFileName = 'agent-testing.jar'

  // rewrite library instrumentation dependencies
  relocate "io.opentelemetry.instrumentation", "io.opentelemetry.javaagent.shaded.instrumentation"

  // Prevents conflict with other SLF4J instances. Important for premain.
  relocate 'org.slf4j', 'io.opentelemetry.javaagent.slf4j'
  // rewrite dependencies calling Logger.getLogger
  relocate 'java.util.logging.Logger', 'io.opentelemetry.javaagent.bootstrap.PatchLogger'

  // prevents conflict with library instrumentation
  relocate 'io.opentelemetry.instrumentation.api', 'io.opentelemetry.javaagent.shaded.instrumentation.api'

  // relocate OpenTelemetry API usage
  relocate "io.opentelemetry.api", "io.opentelemetry.javaagent.shaded.io.opentelemetry.api"
  relocate "io.opentelemetry.semconv", "io.opentelemetry.javaagent.shaded.io.opentelemetry.semconv"
  relocate "io.opentelemetry.spi", "io.opentelemetry.javaagent.shaded.io.opentelemetry.spi"
  relocate "io.opentelemetry.context", "io.opentelemetry.javaagent.shaded.io.opentelemetry.context"

  // relocate the OpenTelemetry extensions that are used by instrumentation modules
  // these extensions live in the AgentClassLoader, and are injected into the user's class loader
  // by the instrumentation modules that use them
  relocate "io.opentelemetry.extension.aws", "io.opentelemetry.javaagent.shaded.io.opentelemetry.extension.aws"
  relocate "io.opentelemetry.extension.kotlin", "io.opentelemetry.javaagent.shaded.io.opentelemetry.extension.kotlin"

  // this is for instrumentation on opentelemetry-api itself
  relocate "application.io.opentelemetry", "io.opentelemetry"
}

evaluationDependsOn(":testing:agent-for-testing")

tasks.withType(Test).configureEach {
  jvmArgs "-Dotel.javaagent.debug=true"
  jvmArgs "-javaagent:${project(":testing:agent-for-testing").tasks.shadowJar.archiveFile.get().asFile.absolutePath}"
  jvmArgs "-Dotel.initializer.jar=${shadowJar.archiveFile.get().asFile.absolutePath}"
  jvmArgs "-Dinternal.testing.disable.global.library.ignores=true"
  // always run with the thread propagation debugger to help track down sporadic test failures
  jvmArgs "-Dotel.threadPropagationDebugger=true"
  jvmArgs "-Dotel.internal.failOnContextLeak=true"
  // always print muzzle warnings
  jvmArgs "-Dio.opentelemetry.javaagent.slf4j.simpleLogger.log.muzzleMatcher=warn"
  // prevent sporadic gradle deadlocks, see SafeLogger for more details
  jvmArgs "-Dotel.internal.enableTransformSafeLogging=true"

  dependsOn shadowJar
  dependsOn ":testing:agent-for-testing:shadowJar"

  // We do fine-grained filtering of the classpath of this codebase's sources since Gradle's
  // configurations will include transitive dependencies as well, which tests do often need.
  classpath = classpath.filter {
    // 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.
    if (file("$buildDir/resources/main").equals(it) || file("$buildDir/classes/java/main").equals(it)) {
      return false
    }
    // If agent depends on library instrumentation, it will be packaged into the testing jar so we
    // need to make sure to exclude from the test classpath.
    if (it.absolutePath.startsWith(file("${projectDir.parent}/library/build/libs").absolutePath)) {
      return false
    }
    return true
  }
}

configurations.configureEach {
  if (it.name.toLowerCase().endsWith('testruntimeclasspath')) {
    // Added by agent, don't let Gradle bring it in when running tests.
    exclude module: 'javaagent-bootstrap'
  }
}
