# Build the mdBook documentation on every push to master and every PR that
# touches docs/, so a broken book is caught. Deploy to GitHub Pages only when
# the repo variable PAGES_ENABLED is 'true' (Pages is not enabled on
# gburd/mentat yet; enable it with Source = GitHub Actions, then set the var).

name: docs

on:
  push:
    branches: [master]
    paths:
      - 'docs/**'
      - '.github/workflows/docs.yml'
  pull_request:
    paths:
      - 'docs/**'
      - '.github/workflows/docs.yml'
  workflow_dispatch:

permissions:
  contents: read

# Never cancel a Pages deploy half-way; superseded PR builds may be cancelled.
concurrency:
  group: docs-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
  build:
    name: Build documentation
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install mdBook
        run: |
          mkdir -p "$HOME/.local/bin"
          curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.44/mdbook-v0.4.44-x86_64-unknown-linux-gnu.tar.gz \
            | tar xz -C "$HOME/.local/bin"
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"

      - name: Build book
        working-directory: docs
        run: mdbook build

      - name: Upload artifact
        if: vars.PAGES_ENABLED == 'true' && github.ref == 'refs/heads/master'
        uses: actions/upload-pages-artifact@v3
        with:
          path: docs/book

  deploy:
    name: Deploy to Pages
    needs: build
    if: vars.PAGES_ENABLED == 'true' && github.ref == 'refs/heads/master'
    runs-on: ubuntu-latest
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
