---
include:
  - remote: https://jobs.just-ci.dev/v6.29.5/container/image.yml

variables:
  DOCKER_EXTRA_ARGS: ""

.docker:
  stage: build
  extends: [".image:rules", ".image:name"]
  image:
    name: docker.io/docker:git
    entrypoint: [""]
  variables:
    DOCKER_HOST: tcp://docker:2375/
  services:
    - name: docker.io/docker:dind
      alias: docker
      command: ["dockerd", "-H", "tcp://0.0.0.0:2375", "--tls=false"]
  script:
    - !reference [".image:name", script]
    - |
      if [ "${IMAGE_ARCHITECTURES}" != "" ]; then
        DOCKER_EXTRA_ARGS="${DOCKER_EXTRA_ARGS} --platform ${IMAGE_ARCHITECTURES}"
        docker run --rm --pull always --quiet --privileged multiarch/qemu-user-static --reset -p yes
      fi

    - docker buildx inspect --bootstrap
    - echo "${CI_REGISTRY_PASSWORD}" | docker login ${CI_REGISTRY} -u
      ${CI_REGISTRY_USER} --password-stdin
    - docker buildx create --use
    - |
      if [ "${DOCKER_EXTRA_ARGS}" != "" ]; then
        echo "[*] Applying the extra arguments '${DOCKER_EXTRA_ARGS}'."
      fi
    - |
      if [ "${IMAGE_CACHE}" = "true" ]; then
        DOCKER_EXTRA_ARGS="${DOCKER_EXTRA_ARGS} --cache-to type=registry,ref=${IMAGE_NAME}:build-cache,mode=max"
        DOCKER_EXTRA_ARGS="${DOCKER_EXTRA_ARGS} --cache-from type=registry,ref=${IMAGE_NAME}:build-cache"
      fi
    # prettier-ignore
    - >
      docker buildx build --push
      --tag ${IMAGE_NAME}:${IMAGE_TAG}
      --tag ${IMAGE_NAME}:${IMAGE_DEV_TAG}
      -f ${IMAGE_CONTAINERFILE} ${DOCKER_EXTRA_ARGS} ${IMAGE_CONTEXT}
