name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build:
    name: Build Release Artifacts
    strategy:
      matrix:
        include:
          - runs-on: ubuntu-24.04
            nix-system: x86_64-linux
            artifact-name: nixtopsy-x86_64-linux
          - runs-on: ubuntu-24.04-arm
            nix-system: aarch64-linux
            artifact-name: nixtopsy-aarch64-linux
    runs-on: ${{ matrix.runs-on }}
    steps:
      - uses: actions/checkout@v5

      - uses: DeterminateSystems/nix-installer-action@main
      - uses: DeterminateSystems/magic-nix-cache-action@main
        with:
          use-flakehub: false

      - name: Build release binary
        run: nix build .#nixtopsy --system ${{ matrix.nix-system }}

      - name: Prepare artifact
        run: |
          mkdir -p artifact
          cp result/bin/nixtopsy artifact/
          cp LICENSE README.md artifact/

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

  release:
    name: Create Release
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Create release archives
        run: |
          mkdir -p release
          cd artifacts
          for dir in */; do
            artifact="${dir%/}"
            cd "$artifact"
            tar czf "../../release/${artifact}.tar.gz" *
            cd ..
          done

      - name: Create release
        uses: softprops/action-gh-release@v2
        with:
          files: release/*

  publish-crates:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - uses: actions/checkout@v5

      - name: Set up Rust
        uses: actions-rust-lang/setup-rust-toolchain@v1

      - name: Authenticate with crates.io
        uses: rust-lang/crates-io-auth-action@v1
        id: auth

      - name: Publish to crates.io
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
