name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build:
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            name: linux-x86_64
          - target: x86_64-apple-darwin
            os: macos-latest
            name: macos-x86_64
          - target: aarch64-apple-darwin
            os: macos-latest
            name: macos-arm64

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

    steps:
      - uses: actions/checkout@v4

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

      - name: Build
        run: cargo build --release --target ${{ matrix.target }}

      - name: Package
        run: |
          cd target/${{ matrix.target }}/release
          tar czf ../../../bitart-${{ github.ref_name }}-${{ matrix.name }}.tar.gz bitart
          cd ../../..

      - name: Upload to Release
        uses: softprops/action-gh-release@v2
        with:
          files: bitart-${{ github.ref_name }}-${{ matrix.name }}.tar.gz

  publish-crate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Publish to crates.io
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }} --allow-dirty

  publish-npm:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org
      - name: Publish to npm
        working-directory: npm
        run: |
          VERSION=${GITHUB_REF_NAME#v}
          npm version $VERSION --no-git-tag-version --allow-same-version
          npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
