name: documentation

on:
  pull_request_target:
    types:
      - closed
  workflow_dispatch:

permissions:
  contents: write

jobs:
  docs:
    if: ${{ github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'main' }} || ${{ github.event_name == 'workflow_dispatch' }}
    runs-on: [self-hosted]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.10'
      - name: Build docs
        run: |
          chmod +x ./maint/scripts/build_docs.sh
          ./maint/scripts/build_docs.sh
      - name: Push to another repo
        env:
          TARGET_REPO: ${{ secrets.TARGET_REPO }}
          TARGET_TOKEN: ${{ secrets.TARGET_TOKEN }}
        run: |
          git config --local user.name "github-actions[bot]"
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git clone https://github.com/${TARGET_REPO}.git target_repo
          cd target_repo
          git checkout main
          find . -mindepth 1 -maxdepth 1 ! -name ".github" ! -name "." ! -name ".git" -exec rm -rf {} +
          cp -r ../docs/_build/html/* ./
          git add .
          if [[ -n "$(git status --porcelain)" ]]; then
          # If there are changes, commit and push
            git commit -m "Update docs"
            git push https://github-actions[bot]:$TARGET_TOKEN@github.com/${TARGET_REPO}.git main
          else
            echo "No changes detected, skipping commit and push."
          fi

