name: Publish

on:
  push:
    tags:
      - 'v*'

env:
  MACOSX_DEPLOYMENT_TARGET: '10.13'

jobs:
  build:
    name: Build — ${{ matrix.target }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: macos-latest
            target: aarch64-apple-darwin
          - os: macos-latest
            target: x86_64-apple-darwin
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: windows-latest
            target: x86_64-pc-windows-msvc

    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - uses: oven-sh/setup-bun@v2

      - run: bun install

      - name: Build native addon
        run: bun run build -- --target ${{ matrix.target }}
        shell: bash

      - uses: actions/upload-artifact@v4
        with:
          name: bindings-${{ matrix.target }}
          path: '*.node'
          if-no-files-found: error

  publish:
    name: Publish to npm
    needs: build
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: actions/download-artifact@v4
        with:
          merge-multiple: true

      - name: List binaries
        run: ls -la *.node

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

      - name: Set version from tag
        run: npm version "${GITHUB_REF_NAME#v}" --no-git-tag-version

      - name: Publish
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

  publish-crates:
    name: Publish to crates.io
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Set version from tag
        run: sed -i "s/^version = \".*\"/version = \"${GITHUB_REF_NAME#v}\"/" Cargo.toml

      - name: Publish
        run: cargo publish --no-verify
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
