name: Rebuild and Publish to PyPI

on:
  push:
    branches:
        - master
  
jobs:
  deploy:
    runs-on: ubuntu-latest
    if: ${{ !contains(github.event.head_commit.message, '[skip ci]') }}

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        ref: master
    
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.10'
        cache: 'pip'

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install hatch
        pip install setuptools wheel twine
        pip install build
        pip install sphinx
        pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu

    - name: Install package in editable mode
      run: |
        pip install -e .
    
    - name: Bump version
      run: |
        python bump_version.py
    
    - name: Get new version
      id: get_new_version
      run: |
        echo "new_version=$(cat new_version.txt)" >> $GITHUB_ENV
        rm new_version.txt
    
    - name: Build the package
      run: |
        python -m build
    
    - name: Publish to PyPI
      env:
        PYPI_USERNAME: ${{ secrets.PYPI_USERNAME }}
        PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
      run: |
        twine upload dist/* -u $PYPI_USERNAME -p $PYPI_PASSWORD
    
    - name: Build Sphinx documentation
      run: |
        make -f Makefile html

    - name: Commit updated version
      run: |
        git config --global user.name 'github-actions[bot]'
        git config --global user.email 'github-actions[bot]@users.noreply.github.com'
        git fetch origin
        git checkout master
        git add pyproject.toml docs/_build/html
        git commit -m "Bump version to ${{ env.new_version }} and update documentation [skip ci]"
        git push origin master
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}