---
# This job will create or update any badges set through other jobs
# 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*"
# To create your own automatic badges, add the following global variables to a job:
# variables:
#   BADGE_job_name: "label-message-color"  # See https://shields.io/
#   BADGE_job_name_URL: "https://some_url/${WITH_VARIABLES}"
# Make sure job_name is replaced and unique, and only contains ASCII or underscores

badge:
  image: registry.gitlab.com/notno/tool/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
    - |
      IFS='-'
      for BADGE_VARIABLE in ${!BADGE_@}; do
        case "${BADGE_VARIABLE}" in *_URL) continue;; esac

        read -ra BADGE_ELEMENTS <<< "${!BADGE_VARIABLE}"
        BADGE_NAME="${BADGE_ELEMENTS[0]}"
        BADGE_URL_VARIABLE=${BADGE_VARIABLE}_URL
        BADGE_URL=${!BADGE_URL_VARIABLE}

        if [ -z "${BADGE_URL}" ]; then
          BADGE_URL="${CI_PROJECT_URL}"
        fi

        echo "[*] Creating/updating badge '${BADGE_NAME}'..."
        BADGE_ID=$(curl --silent --fail --header "PRIVATE-TOKEN: ${GL_TOKEN}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/badges" | jq --arg BADGE_NAME "${BADGE_NAME}" '.[] | select(.name==$BADGE_NAME) | .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 '${BADGE_NAME}' id is ${BADGE_ID}."
        fi

        IMAGE_URL="https://img.shields.io/badge/${!BADGE_VARIABLE}"

        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=${BADGE_URL}&name=${BADGE_NAME}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/badges" >/dev/null && echo "[+] Badge '${BADGE_NAME}' created successfully." || echo "[!] Badge '${BADGE_NAME}' creation failed" ;;
          *) echo "[*] Updating badge..." && curl --silent --fail --request PUT --header "PRIVATE-TOKEN: ${GL_TOKEN}" --data "image_url=${IMAGE_URL}&link_url=${BADGE_URL}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/badges/${BADGE_ID}" >/dev/null && echo "[+] Badge '${BADGE_NAME}' updated successfully." || echo "[!] Badge '${BADGE_NAME}' update failed" ;;
        esac
      done
  rules:
    - if: '$CI_COMMIT_TAG =~ /^v[0-9]+(\.[0-9]+){2}$/'
  needs: []
