---
# https://github.com/GoogleContainerTools/kaniko

# DEV image&tag: the one to always be used for followup jobs (in branches, master, tags etc)
# global variable for easy override
variables:
  KANIKO_REGISTRY_IMAGE: ${CI_REGISTRY_IMAGE}
  KANIKO_DEV_REGISTRY_IMAGE: ${CI_REGISTRY_IMAGE}/dev
  KANIKO_TAG: ${CI_COMMIT_SHORT_SHA}
  KANIKO_DEV_TAG: ${CI_COMMIT_SHORT_SHA}
  KANIKO_CONTEXT: ${CI_PROJECT_DIR}
  KANIKO_DOCKERFILE: "Dockerfile"  # Can be a path
  KANIKO_EXTRA_ARGS: ""  # See https://github.com/GoogleContainerTools/kaniko#additional-flags
  KANIKO_CACHE: "true"

.kaniko:
  stage: build
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  script:
    - echo "{\"auths\":{\"$CI_REGISTRY\":{\"auth\":\"$(echo -n ${CI_REGISTRY_USER}:${CI_REGISTRY_PASSWORD} | base64)\"}}}" > /kaniko/.docker/config.json
    - /kaniko/executor --cache=${KANIKO_CACHE} --context=${KANIKO_CONTEXT} --dockerfile=${KANIKO_DOCKERFILE} --destination=${KANIKO_DEV_REGISTRY_IMAGE}:${KANIKO_DEV_TAG} --destination=${KANIKO_REGISTRY_IMAGE}:${KANIKO_TAG} ${LABELS} ${KANIKO_EXTRA_ARGS}
  rules:  # rules alter the tag used for the second destination
    # master/main
    - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
      variables:
        KANIKO_TAG: "latest"
    # tags
    - if: $CI_COMMIT_TAG
      variables:
        KANIKO_TAG: $CI_COMMIT_TAG
    # branches
    - if: $CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH
      variables:
        KANIKO_REGISTRY_IMAGE: ${KANIKO_REGISTRY_IMAGE}/branch
        KANIKO_TAG: ${CI_COMMIT_REF_SLUG}

# default for polirepos
kaniko:
  extends: .kaniko

# monorepos: user should extend this hidden job (one job for each container)
.kaniko:monorepo:
  extends: .kaniko
  variables:
    CONTEXT_PATH: changeme
    KANIKO_REGISTRY_IMAGE: ${CI_REGISTRY_IMAGE}/${CONTEXT_PATH}
    KANIKO_CONTEXT: ${CI_PROJECT_DIR}/${CONTEXT_PATH}
    KANIKO_DOCKERFILE: ${CI_PROJECT_DIR}/${CONTEXT_PATH}/Dockerfile
