---
# https://github.com/semantic-release/semantic-release#commit-message-format
# https://levelup.gitconnected.com/semantic-versioning-and-release-automation-on-gitlab-9ba16af0c21
include:
  - remote: https://jobs.just-ci.dev/HEAD/project-automation/generic.yaml

semantic-release:
  extends: .release:rules
  image: registry.gitlab.com/just-ci/images/node:alpine
  stage: .post
  variables:
    NPM_PACKAGES:
      semantic-release @semantic-release/gitlab @semantic-release/git
      @semantic-release/changelog @semantic-release/exec
  script:
    - !reference [".release:install", script]
    - dasel --version

    - |
      if ! test -f .releaserc; then
        echo "[+] Using default .releaserc."
        wget -O .releaserc "${DEFAULT_RELEASERC:-https://gitlab.com/just-ci/templates/-/raw/v6.31.2/project-automation/release/releaserc-default.json}"
      fi

    - |
      if [ "$(dasel -f .releaserc -r json 'plugins.all().filter(equal(type(),array)).all().filter(equal(type(),object)).assets.all().count()')" = "0" ] && [ "${DISABLE_AUTO_RELEASE_ASSETS}" = "" ]; then
        echo "[-] No assets set in .releaserc."
        if test -f tbump.toml; then
          SOURCE_FILE=tbump.toml
          DASEL_PATH=.file
        elif test -f pyproject.toml; then
          SOURCE_FILE=pyproject.toml
          DASEL_PATH=.tool.tbump.file
        else
          echo "[-] No tbump.toml or pyproject.toml to retrieve assets. Not pushing assets."
        fi
      fi

    - |
      if [ "${SOURCE_FILE}" != "" ]; then
        TBUMP_FILES=$(dasel -f ${SOURCE_FILE} -r toml -w yaml "${DASEL_PATH}.all().src")
        if [ "${TBUMP_FILES}" = "null" ]; then
          echo "[-] No files set. Not pushing assets."
        else
          if [ "${RELEASE_CHANGELOG:-true}" = "true" ]; then
            TBUMP_FILES="${TBUMP_FILES} CHANGELOG.md"
          fi
          for FILE in ${TBUMP_FILES} ${SOURCE_FILE}; do
            if [ $(dasel -f .releaserc -r json "plugins.all().filter(equal(type(),array)).all().filter(equal(type(),object)).assets.all().filter(equal(.,${FILE})).count(),0.moreThan(.,0)") = "false" ]; then
              dasel put -f .releaserc -t string -r json -w json -v "${FILE}" 'plugins.all().filter(equal(type(),array)).all().filter(equal(type(),object)).assets.append()'
              echo "[+] Added ${FILE} to .releaserc."
            fi
          done
        fi
      fi
    - export GIT_AUTHOR_EMAIL="$(curl -s -X GET -H "PRIVATE-TOKEN:$GL_TOKEN"
      "${CI_API_V4_URL}/user" | jq -r '.email')"
    - export GIT_COMMITTER_EMAIL="${GIT_AUTHOR_EMAIL}"
    - semantic-release ${SEMANTIC_RELEASE_EXTRA_ARGS}
  dependencies:
    - tbump
  artifacts:
    paths:
      - .releaserc
    when: always

semantic-release:GL_TOKEN:
  extends: .fix:GL_TOKEN
  variables:
    JOB_NAME: semantic-release
