# link: https://packaging.python.org/en/latest/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/
name: publish distributions 📦 to PyPI and TestPyPI

on:
  push:
    branches:
      - main
    tags:
      - v*

# activate miniconda environment
# link: https://github.com/marketplace/actions/provision-with-micromamba#IMPORTANT
defaults:
  run:
    shell: bash -l {0}

jobs:
  build-n-publish:
    if: github.repository_owner == 'insarlab'

    name: Build and publish Python 🐍 distributions 📦 to PyPI and TestPyPI
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0

    - name: Set up Python 3.10
      uses: actions/setup-python@v3
      with:
        python-version: "3.10"

    # link: https://github.com/marketplace/actions/provision-with-micromamba
    - name: Install Conda environment with Micromamba
      uses: mamba-org/provision-with-micromamba@main
      with:
        environment-file: environment.yml

    - name: Install pypa/build
      run: >-
        python -m
        pip install
        build
        --user

    - name: Build a binary wheel and a source tarball
      run: >-
        python -m
        build
        --sdist
        --no-isolation    # not install in an isolated environment
        --outdir dist/
        .
        # skip due to the bad request error from pypi:
        # binary wheel has an unsupported platform tag 'linux_x86_64'
        #--wheel

    - name: Publish developed version 📦 to Test PyPI
      if: startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main'
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        password: ${{ secrets.TEST_PYPI_API_TOKEN }}
        repository_url: https://test.pypi.org/legacy/
        skip_existing: false
        verbose: true

    - name: Publish released version 📦 to PyPI
      if: startsWith(github.ref, 'refs/tags/v')
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        password: ${{ secrets.PYPI_API_TOKEN }}
        verbose: true
