stages:
  - build

.docker_build: &docker_build
  stage: build
  image: docker:latest
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay2
    IMAGE_TAG: $CI_REGISTRY_IMAGE/ci:$CI_COMMIT_SHA
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker pull $CI_REGISTRY_IMAGE:master || true  # Retrieve "master" version to use it as cache since the build is run using DinD

docker_ci_image:
  <<: *docker_build
  script:
    - docker build --cache-from $CI_REGISTRY_IMAGE:master -t $IMAGE_TAG .
    - docker push $IMAGE_TAG

docker_image:
  <<: *docker_build
  script:
    - docker build --cache-from $CI_REGISTRY_IMAGE:master -t $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME
  only:
    - master
    - tags
