name: CI

on:
  push:
    branches:
      - main
    tags: [ 'v*' ]
  pull_request:
  workflow_dispatch:

jobs:
  check:
    name: Check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - run: rustup show
      - run: cargo check

  test:
    name: Test Suite
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
    steps:
      - uses: actions/checkout@v6
      - run: rustup show
      - name: Cache cargo build
        uses: Swatinem/rust-cache@v2
      - run: cargo test
      - name: Install LLVM
        if: matrix.os == 'ubuntu-latest'
        run: sudo apt-get install -y llvm
      - name: Install LLVM
        if: matrix.os == 'macos-latest'
        run: |
          brew install llvm
          echo "$(brew --prefix llvm)/bin" >> $GITHUB_PATH
      - name: Run llvm-dlltool
        run: |
          llvm-dlltool -m i386:x86-64 -d tests/python39.def -l llvm-amd64-python39.lib
          llvm-dlltool -m i386 -d tests/python39.def -l llvm-i386-python39.lib
        if: matrix.os != 'windows-latest'
      - name: Compare with llvm-dlltool
        # TOFIX: fix this on macOS
        if: matrix.os == 'ubuntu-latest'
        run: |
          set -e
          if cmp -s -- amd64-python39.lib llvm-amd64-python39.lib; then
            echo "Success!";
          else
            echo "Fail!";
            exit 1;
          fi

          if cmp -s -- i386-python39.lib llvm-i386-python39.lib; then
            echo "Success!";
          else
            echo "Fail!";
            exit 1;
          fi

  fuzz:
    name: Fuzz Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@nightly
      - name: Cache cargo build
        uses: Swatinem/rust-cache@v2
      - name: Cache fuzz corpus - Step 1
        uses: actions/cache@v5
        with:
          path: fuzz/corpus
          key: ${{ runner.os }}-fuzz-corpus
      - name: Cache fuzz corpus - Step 2
        uses: actions/cache@v5
        with:
          path: fuzz/corpus
          key: ${{ runner.os }}-fuzz-corpus-${{ hashFiles('fuzz/corpus/**/*') }}
          restore-keys: |
            ${{ runner.os }}-fuzz-corpus-${{ hashFiles('fuzz/corpus/**/*') }}
            ${{ runner.os }}-fuzz-corpus-
      - uses: dtolnay/install@master
        with:
          crate: cargo-fuzz
      - name: cargo fuzz
        run: cargo fuzz run fuzz_implib -- -runs=100000 -max_len=10485760 -dict=fuzz/dict.txt

  fmt:
    name: Rustfmt
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - run: rustup show
      - run: rustup component add rustfmt
      - name: cargo fmt
        run: cargo fmt --all -- --check
