name: "Automatic Releaser"

on:
  push:
    branches:
      - master

permissions:
  contents: write

jobs:
  check-commit:
    runs-on: ubuntu-latest
    outputs:
      msg_check: ${{ steps.check-msg.outputs.match }}
    steps:
      - name: Check Message
        id: check-msg
        run: |
          pattern="^Release v[0-9]+.[0-9]+.[0-9]+ #(minor|major|patch)$"
          if [[ "${{ github.event.head_commit.message }}" =~ ${pattern} ]]; then
              echo ::set-output name=match::true
          fi
  create-tag:
    runs-on: ubuntu-latest
    if: needs.check-commit.outputs.msg_check == 'true'
    needs: check-commit
    outputs:
      new_tag: ${{ steps.tagger.outputs.new_tag }}
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: '0'

    - name: Bump version and push tag
      id: tagger
      uses: anothrNick/github-tag-action@1.67.0
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        WITH_V: true
        DEFAULT_BUMP: "none"

  create-release:
    runs-on: ubuntu-latest
    needs: create-tag
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 
        with:
          tag_name: ${{ needs.create-tag.outputs.new_tag }}
          release_name: ${{ needs.create-tag.outputs.new_tag }}
          draft: false
          prerelease: false

  releaser:
    runs-on: ubuntu-latest
    needs: create-release
    steps:
      -
        name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - 
        name: Setup node
        uses: actions/setup-node@v2
        with:
          node-version: '16'
          registry-url: 'https://registry.npmjs.org'

      - run: npm ci

      - run: npm run build

      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

  release:
    runs-on: ubuntu-latest
    needs: ["releaser", "create-tag"]
    name: Release Notification
    steps:
      - name: Get the version
        id: get_version
        run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//}
      - run: |
          echo "{\"text\":\"Vultr-Node : Release https://github.com/${{ github.repository }}/releases/tag/${{ needs.create-tag.outputs.new_tag }} \"}" > mattermost.json
      - uses: mattermost/action-mattermost-notify@master
        env:
          MATTERMOST_WEBHOOK_URL: ${{ secrets.MATTERMOST_WEBHOOK_URL }}
          MATTERMOST_USERNAME: ${{ secrets.MATTERMOST_USERNAME}}
          MATTERMOST_ICON: ${{ secrets.MATTERMOST_ICON }}