# VARIABLES
variables:
  DOCKER_BUILDKIT: 1
  DOCKER_DRIVER: overlay2
  DOCKER_HOST: tcp://localhost:2375
  DOCKER_TLS_CERTDIR: ""

##########################################################################################################

### PIPELINE DEFINITION
stages:
  - build
  - release

##########################################################################################################

### BUILD SECTION
build:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  variables:
    GIT_DEPTH: 1
    DIRECTORY: '.'
  before_script:
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
  script:
    - docker build -t "${CI_REGISTRY_IMAGE}:temp-${CI_PIPELINE_IID}" -f "./${DIRECTORY}/Dockerfile" "./${DIRECTORY}"
    - docker push "${CI_REGISTRY_IMAGE}:temp-$CI_PIPELINE_IID"

##########################################################################################################

### RELEASE SECTION
release:
  stage: release
  image: docker:latest
  services:
    - docker:dind
  variables:
    GIT_STRATEGY: "none"
    GIT_DEPTH: 0
  only:
    - /^development$/
    - /^staging$/
    - /^master$/
  before_script:
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
  script:
    - export VERSION_OLD=temp-$CI_PIPELINE_IID
    - export VERSION_NEW=$CI_COMMIT_REF_SLUG
    - test $CI_COMMIT_REF_SLUG = "master" && { export VERSION_NEW=latest; }
    - echo "Running [$VERSION_NEW] release from [$VERSION_OLD] build!"
    - docker pull $CI_REGISTRY_IMAGE:$VERSION_OLD && ( docker tag $CI_REGISTRY_IMAGE:$VERSION_OLD $CI_REGISTRY_IMAGE:$VERSION_NEW && docker push $CI_REGISTRY_IMAGE:$VERSION_NEW ) || true
