name: CI

on:
  push:
    branches:
      - main
    tags:
      - v[0-9]+.[0-9]+.[0-9]+*
  pull_request:

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [windows-latest, macOS-latest, ubuntu-latest]
        node-version: [12.x, 14.x, 16.x]

    steps:
      - name: Fix git checkout line endings
        run: git config --global core.autocrlf input
      - uses: actions/checkout@v2.3.4
      - name: Setup Node.js
        uses: actions/setup-node@v2.3.0
        with:
          node-version: ${{ matrix.node-version }}
      - name: Windows Setup
        if: matrix.os == 'windows-latest'
        run: npm run prepare-win32
      - name: Install
        run: npm install
      - name: Lint
        run: npm run jshint
      - name: Test
        run: npm run test

  prebuild:
    needs: test
    runs-on: ${{ matrix.os }}-latest
    strategy:
      matrix:
        os: [windows, macOS, ubuntu]
        arch: [x64, arm64]
        exclude:
          - os: windows
            arch: arm64
        include:
          - os: windows
            arch: ia32

    steps:
      - name: Fix git checkout line endings
        run: git config --global core.autocrlf input
      - uses: actions/checkout@v2.3.4
      - name: Setup Node.js
        uses: actions/setup-node@v2.3.0
        with:
          node-version: 12.x
      - name: Windows Setup
        if: matrix.os == 'windows'
        run: npm run prepare-win32
      - name: Install
        run: npm install
      - name: Prebuild binaries
        run: npm run prebuild --v8_enable_pointer_compression=false --v8_enable_31bit_smis_on_64bit_arch=false $([[ $OSTYPE != darwin* ]] && echo --llvm_version=0.0 || true)
        shell: bash
        env:
          PREBUILD_ARCH: ${{ matrix.arch }}
      - name: Upload binaries as an artifact
        uses: actions/upload-artifact@v2.3.1
        with:
          name: prebuild-${{ matrix.os }}-${{ matrix.arch }}
          path: prebuilds

  publish:
    needs: prebuild
    runs-on: ubuntu-latest
    if: github.ref_type == 'tag'

    steps:
      - name: Fix git checkout line endings
        run: git config --global core.autocrlf input
      - uses: actions/checkout@v2.3.4
      - name: Setup Node.js
        uses: actions/setup-node@v2.3.0
        with:
          node-version: 12.x
          registry-url: 'https://registry.npmjs.org'
      - name: Install
        run: npm install
      - name: Download prebuild artifacts
        uses: actions/download-artifact@v2.1.0
        with:
          path: artifacts
      - name: Merge artifacts to prebuilds directory
        run: |
          mkdir prebuilds
          mv artifacts/*/* prebuilds/
          rm -r artifacts
          ls prebuilds
      - name: Publish to npm
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
