# A child pipeline for building and tagging Docker images
#
# Usage
# -----
#
# Include this file from a trigger keyword in a job.
#
#   jobspec:
#     rules:
#       - Dockerfile
#       - entrypoint.sh
#       - src/*
#     trigger:
#       project: dom/project-templates
#       ref: main
#       file: pipeline-templates/build-image.yml
#       strategy: depend
#
# Multiple images can be built by combining with the "parallel.matrix" keyword.
# In this case the TARGET variable can be set to select both the target
# stage in the Dockerfile, as well as the output repository name.
#
#   jobspec:
#     parallel:
#       matrix:
#       - TARGET: [first-image, second-image]
#     trigger:
#       project: dom/project-templates
#       ref: main
#       file: pipeline-templates/build-image.yml
#       strategy: depend
#
#
# Variables
# ---------
#
# RELEASE:
#   Set to a release version string to tag the built images as releases
#
# TARGET:
#   The name of a stage from *Dockerfile* to produce as a build image, which
#   will also be included in the repo name of the image
#   (default: unused)
#
# PLATFORMS:
#   A comma separated list of Docker/OCI platforms to build images for
#   (default: linux/amd64, linux/arm64)


variables:
  PLATFORMS:
    value: linux/amd64,linux/arm64
    description: Docker/OCI platform specifiers for built images to target;
      comma separated


workflow:
  # Ensure pipeline can run when triggered from MR pipelines
  rules:
  - when: always


Build:
  stage: build
  image: docker.kodo.org.uk/ci-images/buildkit/buildctl:build-38
  tags: [buildkit]
  script:
  - |
    tee build.env <<ENV
    BUILD_TAG=${CI_REGISTRY_IMAGE}/build${TARGET+/$TARGET}:pipeline-${CI_PIPELINE_IID}
    ENV
    . build.env
  - |
    : buildctl build ...
    opts() { test $# -eq 0 || printf " --opt\0build-arg:%s\0" "$@"; }
    build()
    {
      opts "$@" | xargs -0 buildctl build \
      --frontend dockerfile.v0 \
      --local context=. \
      --local dockerfile=. \
      --output type=image,push=true,name=${BUILD_TAG} \
      --opt label:pipeline=${CI_PIPELINE_IID} \
      --opt label:commit=${CI_COMMIT_SHORT_SHA} \
      ${PLATFORMS:+--opt platform=${PLATFORMS// }} \
      ${TARGET+--opt target=$TARGET}
    }
    eval "build ${BUILD_ARGS}"
  artifacts:
    reports:
      dotenv: build.env


Tag Commit:
  stage: build
  image: docker.kodo.org.uk/ci-images/docker-reg:0.2.0
  needs: [Build]
  script:
  - docker-reg ${BUILD_TAG} retag commit-${CI_COMMIT_SHORT_SHA}


Tag Release:
  stage: deploy
  image: docker.kodo.org.uk/ci-images/docker-reg:0.2.0
  needs: [Build]
  rules:
  - if: $RELEASE
    when: manual
  script:
  - docker-reg ${BUILD_TAG} retag ${CI_REGISTRY_IMAGE}${TARGET+/$TARGET}:${RELEASE#v}
  - docker-reg ${BUILD_TAG} retag ${CI_REGISTRY_IMAGE}${TARGET+/$TARGET}:latest
