name: NodeJS
on:
  push:
    tags:
      - 'v*'
    branches:
      - master
  pull_request:
    branches:
      - master

jobs:
  test:
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-2019]
        node: [14, 18]

    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Setup Windows environment
        if: matrix.os == 'windows-2019'
        uses: microsoft/setup-msbuild@v1.1

      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node }}

      - name: Install node-gyp
        run: npm install -g node-gyp

      - name: Build from source
        run: |
          cd bindings/js
          npm --version
          node --version
          npm ci --build-from-source
          npm test

  build:
    #if: github.event_name == 'push' && contains(github.ref, 'refs/tags/')
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-2019]

    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v3

      - name: Install node-gyp and prebuildify
        run: npm install --location=global node-gyp node-gyp-build node-api-headers prebuildify

      - name: Install dependencies
        run: |
          cd bindings/js
          npm install node-gyp-build node-api-headers

      - name: Build
        run: make -C bindings/js

      - name: Test
        run: |
          cd bindings/js
          npm test

      - uses: actions/upload-artifact@v3
        with:
          name: ${{ matrix.os }}.node
          path: bindings/js/prebuilds/*/*.node

  deploy:
    if: github.event_name == 'push' && contains(github.ref, 'refs/tags/')
    needs: [build]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v3
        with:
          registry-url: 'https://registry.npmjs.org'

      - uses: actions/download-artifact@v3
        with:
          path: bindings/js/prebuilds

      - name: Move artifacts
        run: cd bindings/js/prebuilds && mv */* .

      - name: Publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: make -C bindings/js publish
