name: Build and publish Node.js package

on:
  push:
    branches:
      - master
    tags:
      - 'v*'
  workflow_dispatch:

jobs:
  build:
    strategy:
      matrix:
        feature: [core, js]
        os: [macos-11.0, ubuntu-18.04, windows-2019, self-hosted]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v1

      - name: Get version
        id: version
        shell: bash
        run: echo ::set-output name=VERSION::"$([[ "$GITHUB_REF" == refs/tags/v* ]] && echo ${GITHUB_REF#refs/tags/v} || echo '0.0.0')"

      - name: Set up Node.js
        uses: actions/setup-node@master
        with:
          node-version: 15.x

      - name: Set up Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal
          default: true

      - name: Set up GCC (Windows)
        if: runner.os == 'Windows'
        run: .\.github\workflows\gcc.ps1

      - name: Set up Go
        uses: actions/setup-go@v2
        with:
          go-version: '^1.14.0'

      - name: Run prebuild steps
        shell: bash
        run: bash ./prebuild.sh

      - name: Build native module
        working-directory: ./nodejs
        shell: bash
        run: |
          node package.json.gen.js ${{ matrix.feature }}
          npm install
          npm run build
          node compress.js

      - name: Upload to B2
        shell: bash
        run: |
          binary_name="$(node -e 'console.log([process.platform, process.arch].join("__"))')"
          file=nodejs/index.node.gz
          # Use Node.js as sha1sum and/or curl might not exist on macOS or Windows.
          sha1="$(node -e "h=crypto.createHash('sha1'); h.update(fs.readFileSync('$file')); console.log(h.digest('hex'));")"
          # Use upload proxy as b2 CLI isn't available on ARM64.
          url="https://b2-upload.wlin.workers.dev/${{ secrets.CICD_CLI_B2_BUCKET_NAME }}/minify-html/bin/nodejs/${{ steps.version.outputs.VERSION }}/${{ matrix.feature }}/$binary_name.node.gz?sha1=$sha1"
          node << EOD
          const fs = require("fs");
          const https = require("https");
          const req = https.request("$url", {
            method: "POST",
            auth: "${{ secrets.CICD_CLI_B2_KEY_ID }}:${{ secrets.CICD_CLI_B2_APPLICATION_KEY }}",
          });
          req.on("error", err => {
            console.error(err);
            process.exitCode = 1;
          });
          req.on("response", res => {
            console.log("Upload responded with", res.statusCode);
            if (res.statusCode < 200 || res.statusCode > 299) {
              process.exitCode = 1;
            }
            res.on("data", chunk => process.stdout.write(chunk));
            res.on("error", err => {
              console.log("\nEncountered error during response:", err);
              process.exitCode = 1;
            });
          });
          req.end(fs.readFileSync("$file"));
          EOD
  package:
    strategy:
      matrix:
        feature: [core, js]
    runs-on: ubuntu-18.04
    needs: build
    steps:
      - uses: actions/checkout@v1
      - name: Get version
        id: version
        shell: bash
        run: echo ::set-output name=VERSION::"$([[ "$GITHUB_REF" == refs/tags/v* ]] && echo ${GITHUB_REF#refs/tags/v} || echo '0.0.0')"
      - name: Set up Node.js
        uses: actions/setup-node@master
        with:
          node-version: 15.x
      - name: Pack and publish package
        working-directory: ./nodejs
        run: |
          cat << 'EOF' > .npmrc
          package-lock=false
          //registry.npmjs.org/:_authToken=${{ secrets.NPM_AUTH_TOKEN }}
          EOF
          cp ../README.md .
          node package.json.gen.js ${{ matrix.feature }}
          if [[ "${{ steps.version.outputs.VERSION }}" != "0.0.0" ]]; then
            npm publish --access public
          fi
