/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * License); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Build script containing common build tasks for Java SDK Docker images.
 * Should be applied as a script plugin per supported Java version.
 * (see java$VER/build.gradle)
 */

apply plugin: 'org.apache.beam.module'
apply plugin: 'base'
applyDockerNature()

if (!project.hasProperty('imageJavaVersion')) {
    throw new GradleException('imageJavaVersion project property must be set')
}
def javaBaseImage = project.findProperty('javaBaseImage') ?: 'eclipse-temurin'
def imageJavaVersion = project.findProperty('imageJavaVersion')

description = "Apache Beam :: SDKs :: Java :: Container :: Java ${imageJavaVersion} Container"

configurations {
    dockerDependency
    javaHarnessLauncher
    pulledLicenses
}

dependencies {
    dockerDependency project(path: ":sdks:java:container", configuration: "dockerDependency")
    javaHarnessLauncher project(path: ":sdks:java:container", configuration: "javaHarnessLauncher")
}

task copyDockerfileDependencies(type: Copy) {
    from configurations.dockerDependency
    rename 'slf4j-api.*', 'slf4j-api.jar'
    rename 'slf4j-jdk14.*', 'slf4j-jdk14.jar'
    rename 'jcl-over-slf4j.*', 'jcl-over-slf4j.jar'
    rename 'log4j-over-slf4j.*', 'log4j-over-slf4j.jar'
    rename 'log4j-to-slf4j.*', 'log4j-to-slf4j.jar'
    rename 'beam-sdks-java-container-agent.*.jar', 'open-module-agent.jar'
    rename 'beam-sdks-java-harness-.*.jar', 'beam-sdks-java-harness.jar'
    rename 'jamm.*.jar', 'jamm.jar'

    setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
    into "build/target"
}

task copySdkHarnessLauncher(type: Copy) {
    dependsOn ":sdks:java:container:downloadCloudProfilerAgent"
    // if licenses are required, they should be present before this task run.
    mustRunAfter ":sdks:java:container:pullLicenses"

    from configurations.javaHarnessLauncher
    into "build/target"
}

task copyJavaThirdPartyLicenses(type: Copy) {
    from project(':sdks:java:container').layout.buildDirectory.dir('target/third_party_licenses')
    into "build/target/third_party_licenses"
    dependsOn ':sdks:java:container:pullLicenses'
}

task copyGolangLicenses(type: Copy) {
    from project(':release:go-licenses:java').layout.buildDirectory.dir('output')
    into "build/target/go-licenses"
    dependsOn ':release:go-licenses:java:createLicenses'
}

task copyJdkOptions(type: Copy) {
    from "option-jamm.json"
    from "java${imageJavaVersion}-security.properties"
    from "option-java${imageJavaVersion}-security.json"
    into "build/target/options"
}

task skipPullLicenses(type: Exec) {
    executable "sh"
    args "-c", "mkdir -p build/target/go-licenses build/target/options build/target/third_party_licenses && touch build/target/go-licenses/skip && touch build/target/third_party_licenses/skip"
}

def pushContainers = project.rootProject.hasProperty(["isRelease"]) || project.rootProject.hasProperty("push-containers")

docker {
    name containerImageName(
            name: "${project.docker_image_default_repo_prefix}java${imageJavaVersion}_sdk",
            root: project.rootProject.hasProperty(["docker-repository-root"]) ?
                    project.rootProject["docker-repository-root"] :
                    project.docker_image_default_repo_root,
            tag: project.rootProject.hasProperty(["docker-tag"]) ?
                    project.rootProject["docker-tag"] : project.sdk_version)
    // tags used by dockerTag task
    tags containerImageTags()
    dockerfile project.file("../Dockerfile")
    files "./build/"
    buildArgs([
            'pull_licenses': project.rootProject.hasProperty("docker-pull-licenses") ||
                    project.rootProject.hasProperty("isRelease"),
            'base_image': javaBaseImage,
            'java_version': imageJavaVersion,
    ])
    buildx project.useBuildx()
    platform(*project.containerPlatforms())
    load project.useBuildx() && !pushContainers
    push pushContainers
}

if (project.rootProject.hasProperty("docker-pull-licenses") ||
        project.rootProject.hasProperty("isRelease")) {
    project.logger.lifecycle('docker-pull-licenses set, creating go-licenses')
    dockerPrepare.dependsOn copyJavaThirdPartyLicenses
    dockerPrepare.dependsOn copyGolangLicenses
} else {
    project.logger.lifecycle('docker-pull-licenses not set, skipping go-licenses')
    dockerPrepare.dependsOn skipPullLicenses
}
dockerPrepare.dependsOn copySdkHarnessLauncher
dockerPrepare.dependsOn copyDockerfileDependencies
dockerPrepare.dependsOn copyJdkOptions
