name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write
  id-token: write

jobs:
  build:
    name: Build (${{ matrix.target }})
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
          - target: aarch64-apple-darwin
            os: macos-latest
    steps:
      - uses: actions/checkout@v6

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

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

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

      - name: Test
        run: cargo test --target ${{ matrix.target }}

      - name: Package
        run: |
          tag="${GITHUB_REF_NAME}"
          staging="nnc-${tag}-${{ matrix.target }}"
          mkdir "$staging"
          cp target/${{ matrix.target }}/release/nnc "$staging/"
          cp README.md "$staging/"
          tar czf "${staging}.tar.gz" "$staging"

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: nnc-${{ matrix.target }}
          path: nnc-*-${{ matrix.target }}.*

  release:
    name: Publish Release
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          merge-multiple: true

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          files: nnc-*.tar.gz

  crates:
    name: Publish to crates.io
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

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

      - name: Publish to crates.io
        run: cargo publish --allow-dirty
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
