stages:
  - pre-release
  - release

# Расчет новой версии и формирование Changelog
get_changelog:
  stage: pre-release
  image:
    name: orhunp/git-cliff:latest
    entrypoint: [ "" ]
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline" && $PREPARE_RELEASE == "true"'
    - if: $CI_PIPELINE_SOURCE == "web"
  variables:
    GIT_STRATEGY: clone
    GIT_DEPTH: 0
  script:
    - 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: bitnami/git:latest
  variables:
    GIT_STRATEGY: clone
    GIT_DEPTH: 0
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline" && $PREPARE_RELEASE == "true"'
    - if: $CI_PIPELINE_SOURCE == "web"
  needs:
    - job: get_changelog
      artifacts: true
  script:
    - |
      CURRENT_VERSION=$(git describe --tags --abbrev=0)
      RELEASE_VERSION=$CURRENT_VERSION
      
      # Релиз perxis-proto - это всегда изменения апи и хотфиксом быть не может. Выполняется только при наличии изменений
      if [ $HOTFIX_RELEASE != "true" ] && [ $(git rev-list $CURRENT_VERSION..HEAD --count) -gt 0 ]; then
        RELEASE_VERSION=$PERXIS_RELEASE_VERSION
      fi

      # Если новая версия совпадает со старой, значит изменений не было, и выпускать новый релиз не нужно
      NEEDS_RELEASE=false
      if [ "$RELEASE_VERSION" != "$CURRENT_VERSION" ]; then
        NEEDS_RELEASE=true
      fi

      echo "PERXIS_PROTO_CURRENT_VERSION=$CURRENT_VERSION" >> vars.env
      echo "PERXIS_PROTO_RELEASE_VERSION=$RELEASE_VERSION" >> vars.env
      echo "PERXIS_PROTO_NEEDS_RELEASE=$NEEDS_RELEASE" >> vars.env

      printf '### Release perxis-proto
      PERXIS_RELEASE_VERSION: %s
      HOTFIX_RELEASE: %s
      CURRENT_VERSION: %s
      RELEASE_VERSION: %s
      NEEDS_RELEASE: %s' $PERXIS_RELEASE_VERSION $HOTFIX_RELEASE $CURRENT_VERSION $RELEASE_VERSION $NEEDS_RELEASE
  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" && $PREPARE_RELEASE != "true"
    - if: $CI_PIPELINE_SOURCE == "web"
      when: manual
  script:
    - echo "Start release $VERSION"
    - |
      if [ $NEEDS_RELEASE != "true" ]; then
        exit 203
      fi
  allow_failure:
    exit_codes:
      - 203
  release:
    name: 'Release $VERSION'
    description: '$CI_COMMIT_TAG'
    tag_name: '$VERSION'
