# This job will create or update a version badge containing the latest tag

semantic-release:badge:
  image: registry.gitlab.com/notno/semantic-release-gitlab:latest
  stage: deploy
  script:
    - LATEST_TAG=$(git describe --abbrev=0 --tags)
    - |
      BADGE_ID=$(curl --silent --header "PRIVATE-TOKEN: $GL_TOKEN" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/badges" | jq '.[] | select(.name=="version") | .id') || echo "[-] Unable to get current badge id."
    - LINK_URL="$CI_PROJECT_URL/tags/$LATEST_TAG"
    - IMAGE_URL="https://img.shields.io/badge/version-$LATEST_TAG-informational"
    - |
      case $BADGE_ID in
        ''|*[!0-9]*) echo "[*] Creating badge..." && curl --silent --request POST --header "PRIVATE-TOKEN: $GL_TOKEN" --data "image_url=${IMAGE_URL}&link_url=${LINK_URL}&name=version" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/badges" > /dev/null && echo "[+] Badge created successfully." || echo "[!] Badge creation failed" ;; ;;
        *) curl --silent --request PUT --header "PRIVATE-TOKEN: $GL_TOKEN" --data "image_url=${IMAGE_URL}&link_url=${LINK_URL}" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/badges/$BADGE_ID" > /dev/null && echo "[+] Badge updated successfully." || echo "[!] Badge update failed" ;;
      esac
  rules:
    - if: $CI_COMMIT_TAG && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
