name: Publish

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

env:
  CARGO_TERM_COLOR: always

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: sudo apt-get update && sudo apt-get install -y fish zsh
      - run: rustup show active-toolchain || rustup toolchain install
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --all -- --check
      - run: cargo clippy --all-targets -- -D warnings
      - run: cargo test

  build:
    needs: check
    runs-on: ubuntu-latest
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            asset: aubeshim-linux-x86_64
          - target: x86_64-unknown-linux-musl
            asset: aubeshim-linux-x86_64-musl
          - target: aarch64-unknown-linux-gnu
            asset: aubeshim-linux-aarch64
    steps:
      - uses: actions/checkout@v4
      - run: rustup show active-toolchain || rustup toolchain install
      - run: rustup target add ${{ matrix.target }}
      - name: Install cross tooling
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: sudo apt-get update && sudo apt-get install -y gcc-aarch64-linux-gnu
      - name: Install musl tooling
        if: matrix.target == 'x86_64-unknown-linux-musl'
        run: sudo apt-get update && sudo apt-get install -y musl-tools
      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}
      - env:
          CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
        run: cargo build --release --target ${{ matrix.target }}
      - name: Package
        run: |
          cp target/${{ matrix.target }}/release/aubeshim ${{ matrix.asset }}
          tar -czf ${{ matrix.asset }}.tar.gz ${{ matrix.asset }} README.md LICENSE install.sh
      - uses: softprops/action-gh-release@v2
        with:
          draft: true
          generate_release_notes: true
          files: ${{ matrix.asset }}.tar.gz

  publish-crates:
    needs: check
    runs-on: ubuntu-latest
    environment: crates-io
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v4
      - run: rustup show active-toolchain || rustup toolchain install
      - uses: Swatinem/rust-cache@v2
      - uses: rust-lang/crates-io-auth-action@v1
        id: auth
      - env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
        run: cargo publish --locked
