---
variables:
  IMAGE_DEV_TAG: dev-${CI_COMMIT_SHORT_SHA} # to always be used for follow-up jobs
  IMAGE_CONTEXT: ${CI_PROJECT_DIR}
  IMAGE_CACHE: "true"

.image:rules:
  rules:
    # default branch
    - if: "$CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $IMAGE_TAG == null"
      variables:
        IMAGE_TAG: latest
    # tags
    - if: "$CI_COMMIT_TAG && $IMAGE_TAG == null"
      variables:
        IMAGE_TAG: ${CI_COMMIT_TAG}
    # non-default branches
    - if: "$CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH && $IMAGE_TAG == null"
      variables:
        IMAGE_TAG: ${CI_COMMIT_REF_SLUG}
    # Always run if IMAGE_TAG is set by user
    - if: $IMAGE_TAG

.image:name:
  script:
    - IMAGE_CONTEXT=${IMAGE_CONTEXT/${CI_PROJECT_DIR}\/} # Remove CI_PROJECT_DIR prefix path
    - |
      if [ "${IMAGE_NAME}" = "" ]; then
        if [ "$(realpath ${IMAGE_CONTEXT})" != "$(realpath ${CI_PROJECT_DIR})" ]; then
          if [ "$(echo ${IMAGE_CONTEXT} | tr -cd '/' | wc -c)" -gt 2 ]; then
            echo "[!] Your image path is too deep. The limit is 2. Please set IMAGE_NAME to '\${CI_REGISTRY_IMAGE}/your_name/up_to_here'."
            exit 1
          fi
          IMAGE_NAME=$(echo ${CI_REGISTRY_IMAGE}/${IMAGE_CONTEXT} | tr [:upper:] [:lower:])  # Ensure lowercase
        else
          IMAGE_NAME=${CI_REGISTRY_IMAGE}
        fi
      fi
      echo "IMAGE_NAME=${IMAGE_NAME}" > ${CI_PROJECT_DIR}/image.env
    - |
      echo "[*] Build info:"
      echo "Containerfile: ${IMAGE_CONTAINERFILE:-(default builder value - usually Dockerfile)}"
      echo "Context: ${IMAGE_CONTEXT}"
      echo "Image name: ${IMAGE_NAME}"
      echo "Tags: ${IMAGE_TAG} ${IMAGE_DEV_TAG}"
  artifacts:
    reports:
      dotenv: image.env

# Allows for less problems with a monorepo setup. See pipelines/container.md.
.image:build:
  extends: .kaniko # Default to kaniko.

image:build:
  extends: .image:build
