name: Release

on:
  push:
    tags: ["v*"]

permissions:
  contents: write
  packages: write

jobs:
  build-binaries:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-musl
            artifact: assay-linux-x86_64
            deps: sudo apt-get update && sudo apt-get install -y musl-tools
          - os: macos-14
            target: aarch64-apple-darwin
            artifact: assay-darwin-aarch64
            deps: ""
    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: release-${{ matrix.target }}

      - name: Install dependencies
        if: matrix.deps != ''
        run: ${{ matrix.deps }}

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

      - name: Rename binary
        run: cp target/${{ matrix.target }}/release/assay ${{ matrix.artifact }}

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

  release:
    needs: build-binaries
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/download-artifact@v4
        with:
          pattern: assay-*
          path: artifacts

      - name: Prepare release assets
        run: |
          chmod +x artifacts/assay-linux-x86_64/assay-linux-x86_64
          chmod +x artifacts/assay-darwin-aarch64/assay-darwin-aarch64
          sha256sum artifacts/*/assay-* > checksums-sha256.txt

      - name: Create GitHub Release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh release create ${{ github.ref_name }} \
            artifacts/assay-linux-x86_64/assay-linux-x86_64 \
            artifacts/assay-darwin-aarch64/assay-darwin-aarch64 \
            checksums-sha256.txt \
            --generate-notes

  crates-io:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

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

  docker:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - uses: docker/build-push-action@v6
        with:
          push: true
          tags: |
            ghcr.io/developerinlondon/assay:${{ github.ref_name }}
            ghcr.io/developerinlondon/assay:latest
