---
# Base templates for individual GitLab project setting checks.
# Each check extends one of these and supplies CHECK_* variables.

.gitlab_check:
  stage: test
  image:
    name: ghcr.io/tomwright/dasel:2-alpine
    entrypoint: [""]
  variables:
    GIT_STRATEGY: none
  before_script:
    - apk add -q curl
  rules:
    - if: $GL_TOKEN
  needs: []

# Scalar check against GET /projects/:id.
# Vars: CHECK_KEY, CHECK_EXPECTED, CHECK_HINT.
.gitlab_check_scalar:
  extends: .gitlab_check
  script:
    - >
      curl -sSLf -H "PRIVATE-TOKEN: ${GL_TOKEN}"
      "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}" -o project.json
    - CURRENT=$(dasel -f project.json -r json "${CHECK_KEY}" -w - || echo "error")
    - printf "[*] Checking ${CHECK_KEY}..."
    - |
      if [ "${CURRENT}" = "${CHECK_EXPECTED}" ]; then
        echo -e " \e[32mrecommended value set\e[0m: ${CHECK_EXPECTED}."
      else
        echo -e " \e[31mrecommended value not set\e[0m. Current: ${CURRENT}. Expected: ${CHECK_EXPECTED}."
        echo "${CHECK_HINT}"
        if [ "${GITLAB_RECOMMENDED_AUTO_FIX}" = "true" ]; then
          printf "[*] Automatically fixing the problem..."
          curl -sSLf -H "PRIVATE-TOKEN: ${GL_TOKEN}" -X PUT \
            "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}" \
            -d "${CHECK_KEY}=${CHECK_EXPECTED}" > /dev/null
          echo -e " \e[32mdone\e[0m."
        else
          echo "[!] To resolve automatically, set: GITLAB_RECOMMENDED_AUTO_FIX=true"
          exit 1
        fi
      fi
