stages:
  - pre-release
  - release

# Инициация процесса релиза. Запускается вручную или из восходящего конвейера
get_current_version:
  image: bitnami/git:latest
  stage: pre-release
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline" && $PREPARE_RELEASE == "true"'
    - if: $CI_PIPELINE_SOURCE == "web"
      when: manual
  variables:
    GIT_STRATEGY: clone
    GIT_DEPTH: 0
  script:
    - echo "Start release for perxis-proto"
    - echo CURRENT_VERSION=$(git describe --tags --abbrev=0) >> vars.env
  artifacts:
    reports:
      dotenv: vars.env

# Расчет новой версии и формирование Changelog
get_release_info:
  stage: pre-release
  image:
    name: orhunp/git-cliff:latest
    entrypoint: [ "" ]
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline" && $PREPARE_RELEASE == "true"'
    - if: $CI_PIPELINE_SOURCE == "web"
  needs:
    - job: get_current_version
  variables:
    GIT_STRATEGY: clone
    GIT_DEPTH: 0
  script:
    - echo "RELEASE_VERSION=$(git-cliff --bumped-version)" >> vars.env
    - echo "$(git-cliff --unreleased | sed '1,6d' | sed '$d')" > current_changelog.md
  artifacts:
    reports:
      dotenv: vars.env
    paths:
      - current_changelog.md

# Выпуск релиза и публикация артефактов с новой версией и списком изменений
prepare_release:
  stage: pre-release
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline" && $PREPARE_RELEASE == "true"'
    - if: $CI_PIPELINE_SOURCE == "web"
  needs:
    - job: get_current_version
      artifacts: true
    - job: get_release_info
      artifacts: true
  script:
    - echo "PERXIS_PROTO_CURRENT_VERSION=$CURRENT_VERSION" >> vars.env
    - echo "PERXIS_PROTO_RELEASE_VERSION=$RELEASE_VERSION" >> vars.env
    - |
      # Если новая версия совпадает со старой, значит изменений не было, и выпускать новый релиз не нужно
      NEEDS_RELEASE=false
      if [ "$RELEASE_VERSION" != "$CURRENT_VERSION" ]; then
        NEEDS_RELEASE=true
      fi
    - echo "PERXIS_PROTO_NEEDS_RELEASE=$NEEDS_RELEASE" >> vars.env
  artifacts:
    when: always
    paths:
      - vars.env
      - current_changelog.md
    expire_in: 1 week

# ----- release -----

release:
  stage: release
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  rules:
    - if: $CI_PIPELINE_SOURCE == "pipeline" && $NEEDS_RELEASE == "true"
    - if: $CI_PIPELINE_SOURCE == "web"
      when: manual
  script:
    - echo "Start release $VERSION"
  release:
    name: 'Release $VERSION'
    description: '$CI_COMMIT_TAG'
    tag_name: '$VERSION'
