---
include:
  - remote: https://jobs.just-ci.dev/v6.20.0/project-automation/telemetry.yml

variables:
  IMAGE_NAME: automatic
  IMAGE_CONTAINERFILE: automatic
  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:
    - |
      if [ "${IMAGE_CONTEXT}" = "${CI_PROJECT_DIR}" ]; then
        IMAGE_CONTEXT="."
      else
        IMAGE_CONTEXT=${IMAGE_CONTEXT/${CI_PROJECT_DIR}\/} # Remove prefixed path CI_PROJECT_DIR
      fi
    - |
      if [ "${IMAGE_NAME}" = "automatic" ]; then
        if [ "$(realpath ${IMAGE_CONTEXT})" != "$(realpath ${CI_PROJECT_DIR})" ]; then
          if [ "$(echo ${IMAGE_CONTEXT} | tr -cd '/' | wc -c)" -gt 2 ]; then
            echo "[!] Your context 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
    - |
      if [ "${CI_JOB_NAME}" = "image:build" ]; then
        echo "[+] Setting IMAGE_NAME for subsequent jobs to ${IMAGE_NAME}."
        echo "IMAGE_NAME=${IMAGE_NAME}" > ${CI_PROJECT_DIR}/image.env
      fi
    - |
      if [ "${IMAGE_CONTAINERFILE}" = "automatic" ]; then
        IMAGE_CONTAINERFILE=${IMAGE_CONTEXT}/Dockerfile
      fi
    - |
      echo "[*] Build info:"
      echo "Context: ${IMAGE_CONTEXT}"
      echo "Containerfile: ${IMAGE_CONTAINERFILE#./}"
      echo "Name: ${IMAGE_NAME}"
      echo "Tags: ${IMAGE_TAG} ${IMAGE_DEV_TAG}"
      echo "Cache: ${IMAGE_CACHE}"
  artifacts:
    reports:
      dotenv: image.env

# Extend this one for a default image build in a monorepo
.image:build:
  extends: .kaniko # Default to kaniko.

# Don't extend this one, unless you intend to re-use your first image settings in a monorepo
image:build:
  extends:
    - .image:build
    - .telemetry
