# This job will create or update a version badge containing the latest tag.
# It requires a Project Access Token set as a CI/CD variable called GL_TOKEN
# Also make sure you have set a protected tags wildcard as "v*"
# If you want to disable badges, set a global variable called "I_DONT_LIKE_BADGES"

semantic-release:badge:
  image: bash:latest
  stage: deploy
  script:
    - |
      if [ -z ${GL_TOKEN} ]; then
        echo '$GL_TOKEN is not set. Did you add a Project Access Token with api scope as GL_TOKEN to the CI/CD Variables? If so, it may be set as Protected. You need to add a protected tag wildcard as "v*" for this project.'
        exit 1
      fi
    - apk add --no-cache curl jq
    - |
      echo "[*] Retrieving version badge id..."
      BADGE_ID=$(curl --silent --fail --header "PRIVATE-TOKEN: ${GL_TOKEN}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/badges" | jq '.[] | select(.name=="version") | .id') || true
      if [ -z "${BADGE_ID}" ]; then
        echo "[-] Unable to get badge id. It probably doesn't exist yet, so we'll create a new one."
      else
        echo "Badge id is ${BADGE_ID}."
      fi
    - 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 --fail --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" ;;
        *) echo "[*] Updating badge..." && curl --silent --fail --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: $I_DONT_LIKE_BADGES
      when: never
    - if: '$CI_COMMIT_TAG =~ /^v[0-9]+(\.[0-9]+){2}$/'
  needs: []
