stages:
  - build
  - bundle
  - deploy

Docker:
  # Use the official docker image.
  image: gitlab.jonasled.de/jonasled/buildx-docker:latest
  stage: build
  services:
    - docker:dind
  before_script:
    - docker context create build
    - docker buildx create build --use
    - docker run --privileged --rm tonistiigi/binfmt --install all
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - apk add jq
  # Default branch leaves tagempty (= latest tag)
  # All other branches are tagged with the escaped branch name (commit ref slug)
  script:
    - |
      if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
        tag="latest"
      else
        tag="$CI_COMMIT_REF_SLUG"
      fi
    - docker buildx build --platform linux/arm64,linux/amd64 --push --provenance false --tag "$CI_REGISTRY_IMAGE:${tag}" .
    - export IMAGE_HASH=$(docker buildx imagetools inspect "$CI_REGISTRY_IMAGE:${tag}" --format "{{json .Manifest}}" | jq .digest)
    - "echo \"Image Hash: $IMAGE_HASH\""
    - echo "$IMAGE_HASH" >> image-hash.txt
  artifacts:
      paths:
          - image-hash.txt

Helm:
  stage: bundle
  image: alpine:latest
  dependencies:
      - Docker
  before_script:
    - apk add curl bash openssl git
    - curl -L https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
  script:
      - helm repo add bitnami https://charts.bitnami.com/bitnami
      - helm repo update
      - helm dependency update text2img
      - IMAGE_HASH=$(cat image-hash.txt)

      - "export NEXT_PATCH_VERSION=\"$(cat text2img/Chart.yaml | grep ^version: | cut -d ' ' -f 2 | awk -F. '{print $1 \".\" $2 \".\" $3+1}')\""
      - "sed -i \"s/^  digest: .*/  digest: $IMAGE_HASH/\" text2img/values.yaml"
      - helm package text2img --version "${NEXT_PATCH_VERSION}-rc-${CI_PIPELINE_IID}"
  artifacts:
      paths:
      - text2img-*.tgz

Deploy Helm:
  image: curlimages/curl:latest
  stage: deploy
  script:
    - HELM_TGZ=$(ls text2img-*.tgz)
    - 'curl --request POST --user gitlab-ci-token:$CI_JOB_TOKEN --form "chart=@${HELM_TGZ}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/helm/api/${CI_COMMIT_BRANCH}/charts"'
  dependencies:
    - Helm