name: Render PDF

on:
  push:
    branches:
      - deploy
  workflow_dispatch:

jobs:
  render-pdf:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install TeX
        run: |
          if ! command -v latexmk >/dev/null 2>&1; then
            if ! command -v apt-get >/dev/null 2>&1; then
              echo "latexmk is missing and apt-get is unavailable" >&2
              exit 1
            fi
            if command -v sudo >/dev/null 2>&1; then
              SUDO=sudo
            else
              SUDO=
            fi
            $SUDO apt-get update
            $SUDO apt-get install -y --no-install-recommends \
              latexmk \
              texlive-fonts-recommended \
              texlive-lang-polish \
              texlive-latex-base \
              texlive-latex-extra \
              texlive-latex-recommended
          fi

      - name: Render PDF with commit metadata
        run: ./scripts/render_pdf.sh

      - name: Commit rendered PDF
        run: |
          set -eu
          repo_name="${GITHUB_REPOSITORY#*/}"
          pdf_file="$(find doc/pdf -maxdepth 1 -type f -name '*.pdf' -print -quit)"
          if [ -z "$pdf_file" ]; then
            echo "rendered PDF is missing" >&2
            exit 1
          fi
          remote_sha="$(git ls-remote origin refs/heads/deploy | cut -f1)"
          if [ "$remote_sha" != "$GITHUB_SHA" ]; then
            echo "deploy advanced from $GITHUB_SHA to $remote_sha; skip publishing stale PDF"
            exit 0
          fi
          git config user.name "gitea-actions"
          git config user.email "gitea-actions@noreply.local"
          printf '%s\n' "$GITHUB_SHA" > doc/pdf/source-commit.txt
          git add -u doc/pdf
          git add -f "$pdf_file"
          git add doc/pdf/source-commit.txt
          git diff --cached --quiet && exit 0
          git commit -m "Render ${repo_name} PDF for ${GITHUB_SHA::12} [skip actions]"
          git push origin HEAD:deploy
