name: Build

on:
  push:
    branches: ["master"]
    tags: ["v*"]
  pull_request:
    branches: ["master"]

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always
  BIN_NAME: rik
  # Override local config (like mold) to use default linker in CI
  RUSTFLAGS: ""

jobs:
  fmt:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt
      - run: cargo fmt --all --check

  clippy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy
      - uses: Swatinem/rust-cache@v2
      - run: cargo clippy --all-features -- -D warnings

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo test --all-features

  build:
    name: ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            cmd: cargo
            ext: ""
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            cmd: cross
            ext: ""
          - target: x86_64-apple-darwin
            os: macos-latest
            cmd: cargo
            ext: ""
          - target: aarch64-apple-darwin
            os: macos-latest
            cmd: cargo
            ext: ""
          - target: x86_64-pc-windows-msvc
            os: windows-latest
            cmd: cargo
            ext: ".exe"

    steps:
      - uses: actions/checkout@v6

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

      - name: Install Cross
        if: matrix.cmd == 'cross'
        uses: taiki-e/install-action@cross

      - name: Cache
        uses: Swatinem/rust-cache@v2

      - name: Build
        run: ${{ matrix.cmd }} build --release --target ${{ matrix.target }} --package rik

      - name: Rename Binary
        shell: bash
        run: cp target/${{ matrix.target }}/release/${{ env.BIN_NAME }}${{ matrix.ext }} ${{ env.BIN_NAME }}-${{ matrix.target }}${{ matrix.ext }}

      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ env.BIN_NAME }}-${{ matrix.target }}
          path: ${{ env.BIN_NAME }}-${{ matrix.target }}${{ matrix.ext }}

  release:
    name: Release
    if: startsWith(github.ref, 'refs/tags/')
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          pattern: ${{ env.BIN_NAME }}-*
          merge-multiple: true

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ env.BIN_NAME }}-*
