on:
  push:
    branches: [ master ]

jobs:
  check-release-tag:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Prepare tag
        id: prepare_tag
        continue-on-error: true
        run: |
          export TAG=v$(jq -r '.version' package.json)
          echo "TAG=$TAG" >> $GITHUB_ENV
          export CHECK_TAG=$(git tag | grep $TAG)
          if [[ $CHECK_TAG ]]; then
            echo "Skipping because release tag already exists"
            exit 1
          fi
      - name: Output
        id: release_output
        if: ${{ steps.prepare_tag.outcome == 'success' }}
        run: |
          echo "::set-output name=tag::${{ env.TAG }}"
    outputs:
      tag: ${{ steps.release_output.outputs.tag }}

  build:
    runs-on: ubuntu-latest
    needs: check-release-tag
    if: ${{ needs.check-release-tag.outputs.tag }}
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: 16.x
      - run: yarn install
  
  publish-npm:
    runs-on: ubuntu-latest
    needs: build
    if: ${{ needs.check-release-tag.outputs.tag }}
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: 16.x
          registry-url: https://registry.npmjs.org/
          scope: '@pusher'
      - run: yarn install
      - run: yarn publish --verbose --access public 
        env:
          NODE_AUTH_TOKEN: ${{secrets.NPM_AUTH_TOKEN}}

  create-github-release:
    runs-on: ubuntu-latest
    needs: publish-npm
    if: ${{ needs.check-release-tag.outputs.tag }}
    steps:
      - uses: actions/checkout@v2
      - name: Prepare tag
        run: |
          export TAG=v$(jq -r '.version' package.json)
          echo "PRE_RELEASE=false" >> $GITHUB_ENV
          echo "TAG=$TAG" >> $GITHUB_ENV
      - name: Check pre release
        if: contains(env.TAG, 'beta')
        run: echo "PRE_RELEASE=true" >> $GITHUB_ENV
      - name: Setup git
        run: |
          git config user.email "pusher-ci@pusher.com"
          git config user.name "Pusher CI"
      - name: Prepare description
        run: |
          csplit -s CHANGELOG.md "/##/" {1}
          cat xx01 > CHANGELOG.tmp
      - name: Create Release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ env.TAG }}
          release_name: ${{ env.TAG }}
          body_path: CHANGELOG.tmp
          draft: false
          prerelease: ${{ env.PRE_RELEASE }}
