---
variables:
  INITIAL_SEMANTIC_RELEASE: "" # initial semantic release version, e.g. "0.1.0"

.fix:GL_TOKEN:
  stage: .pre
  image: docker.io/alpine:3
  variables:
    GIT_STRATEGY: none
    JOB_NAME: project automation
  script:
    - echo "[!] For the ${JOB_NAME} job, you need to provide a Protected and
      Masked variable named 'GL_TOKEN' with a {Project, Group, Personal} Access
      Token with 'api' scope."
    - echo "[+] For details, see the README at
      https://gitlab.com/just-ci/templates#how-to-use"
    - exit 1
  allow_failure: true
  rules:
    - if:
        "$CI_COMMIT_REF_PROTECTED == 'true' && $GL_TOKEN == null &&
        $DISABLE_GL_TOKEN_CHECK == null"

.release:rules:
  rules:
    - if:
        "$CI_COMMIT_REF_PROTECTED == 'true' && $GL_TOKEN && $CI_COMMIT_TAG ==
        null"
      exists:
        - tbump.toml
        - pyproject.toml
    - when: never

.release:install:
  script:
    - |
      for PACKAGE in ${NPM_PACKAGES}; do
        if ! npm list -g "${PACKAGE}" >/dev/null; then
          npm install -g "${PACKAGE}"
        fi
      done

.release:patch-initial-version:
  script:
    - |
      if [ ! -z "$INITIAL_SEMANTIC_RELEASE" ]; then
        FIRST_RELEASE_SEARCH_STR="const FIRST_RELEASE"
        NEW_FIRST_RELEASE_STR="$FIRST_RELEASE_SEARCH_STR = \"$INITIAL_SEMANTIC_RELEASE\";"
        SEMANTIC_RELEASE_LIB_DIR="$(npm list -g | head -1)/node_modules/semantic-release/lib/"
        CONSTANTS_PATH=$(grep -rwl $SEMANTIC_RELEASE_LIB_DIR -e "$FIRST_RELEASE_SEARCH_STR")
        sed -i "s/$FIRST_RELEASE_SEARCH_STR.*$/$NEW_FIRST_RELEASE_STR/" $CONSTANTS_PATH
        grep -q "$NEW_FIRST_RELEASE_STR" $CONSTANTS_PATH || echo "[!] Failed to reconfigure the initial release version of semantic-release." 1>&2
        echo "[*] Configured semantic-release to release version \"$INITIAL_SEMANTIC_RELEASE\" if no prior release exists."
      fi
