# 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:
    - |
      if [[ ! ${CI_COMMIT_TAG} =~ ^v[0-9]+(\.[0-9]+){2}$ ]]; then
        echo "[!] Not a version tag in format v#.#.#."
        exit 1
      fi
    - |
      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/${CI_COMMIT_TAG}"
    - IMAGE_URL="https://img.shields.io/badge/version-${CI_COMMIT_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
