/*
 * 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.
 */

plugins { id 'org.apache.beam.module' }
applyGoNature()
applyDockerNature()

description = "Apache Beam :: SDKs :: Go :: Container"

goBuild {
  goTargets = '*.go' // only build the immediate directory.
  outputLocation = './build/target/${GOOS}_${GOARCH}/boot'
}

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

docker {
  name containerImageName(
          name: project.docker_image_default_repo_prefix + "go_sdk",
          root: project.rootProject.hasProperty(["docker-repository-root"]) ?
                  project.rootProject["docker-repository-root"] :
                  project.docker_image_default_repo_root)
  // tags used by dockerTag task
  tags containerImageTags()
  files "./build/"
  buildArgs(['pull_licenses': project.rootProject.hasProperty(["docker-pull-licenses"]) ||
                     project.rootProject.hasProperty(["isRelease"])])
  buildx project.useBuildx()
  platform(*project.containerPlatforms())
  load project.useBuildx() && !pushContainers
  push pushContainers
}
dockerPrepare.dependsOn tasks.named("goBuild")

// Ensure that making the docker image builds any required artifacts
if (project.rootProject.hasProperty(["docker-pull-licenses"])) {
  task copyGolangLicenses(type: Copy) {
    project.logger.lifecycle('docker-pull-licenses set, running go-licenses')
    from "${project(':release:go-licenses:go').buildDir}/output"
    into "build/target/go-licenses"
    dependsOn ':release:go-licenses:go:createLicenses'
  }
  dockerPrepare.dependsOn 'copyGolangLicenses'
} else {
  task skipPullLicenses(type: Exec) {
    project.logger.lifecycle('docker-pull-licenses not set, skipping go-licenses')
    executable "sh"
    // Touch a dummy file to ensure the directory exists.
    args "-c", "mkdir -p build/target/go-licenses && touch build/target/go-licenses/skip"
  }
  dockerPrepare.dependsOn 'skipPullLicenses'
}

task pushAll {
  dependsOn ":sdks:go:container:docker"
}