name: CI

on:
  push:
  pull_request:
  workflow_dispatch:

jobs:
  test-default:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt

      - name: Cache cargo
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: cargo-default-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}

      - name: Format check
        run: cargo fmt --check

      - name: Build default backend
        run: cargo build --verbose

      - name: Test default backend
        run: cargo test --verbose

      - name: Run examples
        run: |
          cargo run --example kem_roundtrip
          cargo run --example dsa_sign_verify
          cargo run --example hkdf_handshake

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

      - uses: dtolnay/rust-toolchain@stable

      - name: Install build deps
        run: |
          sudo apt-get update
          sudo apt-get install -y cmake ninja-build build-essential pkg-config

      - name: Resolve liboqs SHA
        id: liboqs-sha
        run: |
          echo "sha=$(git ls-remote https://github.com/open-quantum-safe/liboqs refs/heads/main | cut -f1)" >> "$GITHUB_OUTPUT"

      - name: Cache liboqs install
        id: cache-liboqs
        uses: actions/cache@v4
        with:
          path: ${{ github.workspace }}/.local/liboqs
          key: liboqs-${{ runner.os }}-${{ steps.liboqs-sha.outputs.sha }}

      - name: Build and install liboqs
        if: steps.cache-liboqs.outputs.cache-hit != 'true'
        env:
          PREFIX: ${{ github.workspace }}/.local/liboqs
          SRC: ${{ runner.temp }}/liboqs-src
        run: |
          rm -rf "$SRC"
          git clone --depth 1 https://github.com/open-quantum-safe/liboqs "$SRC"
          cmake -S "$SRC" -B "$SRC/build" -G Ninja \
            -DCMAKE_BUILD_TYPE=Release \
            -DOQS_DIST_BUILD=ON \
            -DBUILD_SHARED_LIBS=ON \
            -DCMAKE_INSTALL_PREFIX="$PREFIX"
          cmake --build "$SRC/build" --target install

      - name: Export liboqs paths
        env:
          PREFIX: ${{ github.workspace }}/.local/liboqs
        run: |
          echo "LIBOQS_DIR=$PREFIX" >> "$GITHUB_ENV"
          echo "PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig" >> "$GITHUB_ENV"
          echo "LD_LIBRARY_PATH=$PREFIX/lib" >> "$GITHUB_ENV"

      - name: Cache cargo
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: cargo-liboqs-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}

      - name: Build real liboqs backend
        run: cargo build --features "liboqs ml_kem_768 ml_dsa_44" --verbose

      - name: Test real liboqs backend
        run: cargo test --features "liboqs ml_kem_768 ml_dsa_44" --verbose
