# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: Node.js CI

on: [push]

jobs:

  build:

    strategy:
      matrix:
        include:
          - node-version: 18.x   # fastest, so run first, to error fast
            os: ubuntu-latest
          - node-version: 18.x   # slowest, so run next. sort by slowest from here to get earliest end through parallelism
            os: macos-latest
          - node-version: 18.x   # finish check big-3 on latest current
            os: windows-latest
          - node-version: 14.x  # lastly check just ubuntu on historic node versions because speed, oldest (slowest) first
            os: ubuntu-latest
          - node-version: 15.x
            os: ubuntu-latest
          - node-version: 16.x
            os: ubuntu-latest
          - node-version: 17.x
            os: ubuntu-latest

    runs-on: ${{matrix.os}}

    steps:
    - uses: actions/checkout@v1
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - name: npm install, build, and test
      run: |
        npm install && npm run ci_build
      env:
        CI: true

  release:
    if: (github.event.pusher.name == github.event.repository.owner.name) && (github.ref == 'refs/heads/main')
    needs: build
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Export tag to envvars
      run: |
        export TAG=$(awk -F'"' '/"version": ".+"/{ print $4; exit; }' package.json)
        echo "TAG=$TAG" >> $GITHUB_ENV
    - name: Use Node.js 18.x
      uses: actions/setup-node@v1
      with:
        node-version: 18.x
        registry-url: https://registry.npmjs.org/

    - name: Push tags
      run: git push origin --tags

    - name: Create the release
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        tag_name: ${{ env.TAG }}
        release_name: ${{ env.TAG }}
        body_path: CHANGELOG.md

    - name: Publish to npm
      run: |
        npm publish
      env:
        NODE_AUTH_TOKEN: ${{ secrets.NEAT_TS_GH_ACTIONS_PUBLISH_TOKEN }}
