
stages:
- build
- tag

build:
  stage: build
  allow_failure: false
  image:
    name: gcr.io/kaniko-project/executor:v1.20.0-debug
    entrypoint: [""]
  rules:
    - if: $CI_COMMIT_TAG
  script:
    - echo "{\"auths\":{\"$CI_REGISTRY\":{\"auth\":\"$(printf "%s:%s" "${CI_REGISTRY_USER}" "${CI_REGISTRY_PASSWORD}" | base64 | tr -d '\n')\"}}}" > /kaniko/.docker/config.json
    - /kaniko/executor
      --context "${CI_PROJECT_DIR}"
      --dockerfile "${CI_PROJECT_DIR}/Dockerfile"
      --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_TAG}"


.tag-template:
  stage: tag
  image: docker:24.0.7
  rules:
    - if: $CI_COMMIT_TAG
      when: manual
  before_script:
  - mkdir -p $HOME/.docker
  - echo "{\"auths\":{\"$CI_REGISTRY\":{\"auth\":\"$(printf "%s:%s" "${CI_REGISTRY_USER}" "${CI_REGISTRY_PASSWORD}" | base64 | tr -d '\n')\"}}}" > $HOME/.docker/config.json

tag-latest:
  extends: .tag-template
  script:
  - docker buildx imagetools create --tag $CI_REGISTRY_IMAGE:latest $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG 

tag-major:
  extends: .tag-template
  script:
  - export newtag=$(echo $CI_COMMIT_TAG | cut -d. -f 1)
  - docker buildx imagetools create --tag $CI_REGISTRY_IMAGE:$newtag $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG 

tag-minor:
  extends: .tag-template
  script:
  - export newtag=$(echo $CI_COMMIT_TAG | cut -d. -f 1-2)
  - docker buildx imagetools create --tag $CI_REGISTRY_IMAGE:$newtag $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG 
