import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage
import com.bmuschko.gradle.docker.tasks.image.DockerPushImage

plugins {
  id "java"
  id "com.google.cloud.tools.jib" version "3.1.4"
  id "com.bmuschko.docker-remote-api" version "6.7.0"
  id "com.github.johnrengelman.shadow" version "6.1.0"
  id "de.undercouch.download" version "4.1.1"
  id "com.diffplug.spotless" version "6.1.2"
}

group = "io.opentelemetry"
version = "0.0.1-SNAPSHOT"

repositories {
  mavenCentral()
}

compileJava {
  options.release.set(11)
}

spotless {
  java {
    googleJavaFormat()
    licenseHeaderFile(rootProject.file("../../../buildscripts/spotless.license.java"), "(package|import|public)")
    target("src/**/*.java")
  }
}

dependencies {
  implementation("com.linecorp.armeria:armeria-grpc:1.0.0")
  implementation("io.opentelemetry:opentelemetry-proto:1.3.0-alpha")
  implementation("org.slf4j:slf4j-simple:1.7.30")
}

shadowJar {
  manifest {
    attributes "Main-Class": "io.opentelemetry.smoketest.fakebackend.FakeBackendMain"
  }
}

ext {
  extraTag = findProperty("extraTag") ?: new Date().format("yyyyMMdd.HHmmSS")
}

jib {
  from.image = "gcr.io/distroless/java-debian10:11"
  to.image = "ghcr.io/open-telemetry/opentelemetry-java-instrumentation/smoke-test-fake-backend:$extraTag"
}


//windows containers are built manually since jib does not support windows containers yet
def backendDockerBuildDir = new File(project.buildDir, "docker-backend")

task windowsBackendImagePrepare(type: Copy) {
  dependsOn(shadowJar)
  into(backendDockerBuildDir)
  from("src/docker/backend")
  from(shadowJar.outputs) {
    rename { _ -> "fake-backend.jar" }
  }
}

task windowsBackendImageBuild(type: DockerBuildImage) {
  dependsOn(windowsBackendImagePrepare)
  inputDir = backendDockerBuildDir

  it.images.add "ghcr.io/open-telemetry/opentelemetry-java-instrumentation/smoke-test-fake-backend-windows:$extraTag"
  it.dockerFile = new File(backendDockerBuildDir, "windows.dockerfile")
}

tasks.create("dockerPush", DockerPushImage) {
  group = "publishing"
  description = "Push all Docker images for the test backend"
  dependsOn(windowsBackendImageBuild)
  images.set(["ghcr.io/open-telemetry/opentelemetry-java-instrumentation/smoke-test-fake-backend-windows:$extraTag"])
}
