name: release

on:
  workflow_dispatch:
    inputs:
      next_version:
        description: |
          Next release version. Possible values: x.y.z, major, minor, patch (or pre|rc|etc).
          Also, you can pass 'skip' to skip 'git tag' and do 'gem push' for the current version
        required: true
        type: string
    secrets:
      pat_token:
        required: false
jobs:
  release:
    runs-on: ubuntu-latest
    env:
      HAVE_PAT_TOKEN: ${{ secrets.pat_token != '' }}
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: true

      - run: git fetch --tags origin

      - if: ${{ env.HAVE_PAT_TOKEN == 'true' }}
        uses: metanorma/ci/gh-rubygems-setup-action@main
        with:
          token: ${{ secrets.pat_token }}

      # workaround for https://github.com/actions/runner-images/issues/37
      - if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install libcurl4-openssl-dev

      - uses: ruby/setup-ruby@v1
        with:
          ruby-version: '3.1'
          bundler-cache: true

      - run: |
          git config user.name github-actions
          git config user.email github-actions@github.com

      - run: gem install gem-release

      - run: gem bump --version ${{ inputs.next_version }} --tag --push

      - name: publish to rubygems.org
        env:
          RUBYGEMS_API_KEY: ${{ secrets.UNITSML_CI_RUBYGEMS_API_KEY }}
        run: |
          mkdir -p ~/.gem
          envsubst << 'EOF' > ~/.gem/credentials
          ---
          :rubygems_api_key: ${RUBYGEMS_API_KEY}
          EOF
          chmod 0600 ~/.gem/credentials
          bundle exec rake release

      # This workflow usually called via repository_dispatch or direct workflow_dispatch
      # in both cases `github.ref` doesn't reflect real version so we calculate it from gemspecfile
      - name: get current gem ref
        id: gem-tag-ref
        run: |
          GEM_VERSION=$(ruby -e "puts Gem::Specification.load(Dir.glob('*.gemspec').first).version.to_s")
          echo "value=refs/tags/v${GEM_VERSION}" >> $GITHUB_OUTPUT

      - uses: peter-evans/repository-dispatch@v2
        with:
          token: ${{ secrets.pat_token || github.token }}
          repository: ${{ github.repository }}
          event-type: release-passed
          client-payload: '{"ref": "${{ steps.gem-tag-ref.outputs.value }}", "sha": "${{ github.sha }}", "type": "release-passed"}'