name: Build PR documentation

on:
  pull_request:
    branches: [ main ]

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  build_documentation:
    runs-on: ubuntu-latest
    env:
      COMMIT_SHA: ${{ github.event.pull_request.head.sha }}
      PR_NUMBER: ${{ github.event.number }}
      EVENT_CONTEXT: ${{ toJSON(github.event) }}
      PR_CLONE_URL: ${{ github.event.pull_request.head.repo.clone_url }}
      PR_CLONE_NAME: ${{ github.event.pull_request.head.repo.name }}

    steps:
      - uses: actions/checkout@v3
        with:
          repository: 'huggingface/doc-builder'
          path: doc-builder

      - uses: actions/checkout@v3
        with:
          repository: 'huggingface/optimum-graphcore'
          path: optimum-graphcore

      - name: Setup environment
        run: |
          python -m venv doc_builder_venv --clear
          source doc_builder_venv/bin/activate
          pip uninstall -y doc-builder
          cd doc-builder
          git pull origin main
          pip install .
          pip install .[quality]
          cd ..

      - name: Make documentation
        run: |
          source doc_builder_venv/bin/activate
          cd optimum-graphcore
          make doc BUILD_DIR=graphcore-doc-build VERSION=pr_$PR_NUMBER COMMIT_SHA_SUBPACKAGE=$COMMIT_SHA CLONE_URL=$PR_CLONE_URL CLONE_NAME=$PR_CLONE_NAME
          cd ..

      - name: Save commit_sha & pr_number
        run: |
          source doc_builder_venv/bin/activate
          cd optimum-graphcore
          sudo chmod -R ugo+rwx graphcore-doc-build
          cd graphcore-doc-build
          sudo mv optimum.graphcore optimum-graphcore
          echo ${{ env.COMMIT_SHA }} > ./commit_sha
          echo ${{ env.PR_NUMBER }} > ./pr_number

      - uses: actions/upload-artifact@v3
        with:
          name: doc-build-artifact
          path: optimum-graphcore/graphcore-doc-build/
