name: docs

on:
  release:
    types: [published]
  push:
    branches:
      - master
  pull_request:

concurrency:
  group: ${{ github.workflow }}

jobs:
  build-docs-and-publish:
    runs-on: ubuntu-20.04
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v3
      - name: Setup Python
        uses: actions/setup-python@v3
        with:
          python-version: '3.10'
      - name: Get tag
        uses: olegtarasov/get-tag@v2.1
      - name: Install pandoc
        run: sudo apt-get install -y pandoc
      - name: Install Poetry
        uses: snok/install-poetry@v1
      - name: Install package and test dependencies
        run: |
          poetry install --with dev,nbtools
      - name: build sphinx docs
        run: |
          cd docsrc
          poetry run make github
      - name: Determine directory to publish docs to
        id: docs-publish-dir
        uses: jannekem/run-python-script-action@v1
        with:
          script: |
            import os, re
            github_ref = os.environ.get('GITHUB_REF')
            m = re.match(r'^refs/tags/v([0-9]+\.[0-9]+\.[0-9]+(-dev\.[0-9]+)?)$',
                        github_ref)
            if m:
                target = m.group(1)
            elif github_ref == 'refs/heads/master':
                target = 'master'
            else:
                target = ''
            set_output('target', target)
      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        if: steps.docs-publish-dir.outputs.target != ''
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs/html
          destination_dir: ${{ steps.docs-publish-dir.outputs.target }}
          keep_files: false
    outputs:
      docs-target: ${{ steps.docs-publish-dir.outputs.target }}
  update-versions:
    name: Update docs versions JSON
    needs: build-docs-and-publish
    if: needs.build-docs-and-publish.outputs.docs-target != ''
    runs-on: Ubuntu-latest
    permissions:
      contents: write
    steps:
    - uses: actions/checkout@v3
      with:
        ref: gh-pages
    - name: Write versions to JSON file
      uses: jannekem/run-python-script-action@v1
      with:
        script: |
          import json
          import re

          # dependency of sphinx, so should be installed
          from packaging import version as version_
          from pathlib import Path

          cwd = Path.cwd()

          versions = sorted((item.name for item in cwd.iterdir()
                            if item.is_dir() and not item.name.startswith('.')),
                            reverse=True)

          # Filter out master and dev versions
          parseable_versions = []
          for version in versions:
              try:
                  version_.parse(version)
              except version_.InvalidVersion:
                  continue
              parseable_versions.append(version)

          if parseable_versions:
            max_version = max(parseable_versions, key=version_.parse)
          else:
            max_version = None
          target_dir = Path('gh-pages')
          target_dir.mkdir(parents=True)

          versions = [
            dict(
              version=version,
              title=version + ' (stable)' if version == max_version else version,
              aliases=['stable'] if version == max_version else [],
              ) for version in versions
          ]
          target_file = target_dir / 'versions.json'
          with target_file.open('w') as f:
              json.dump(versions, f)

    - name: Publish versions JSON to GitHub pages
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: gh-pages
        keep_files: true
