name: Test & Publish PyPi release

on:
  release:
    types: [created]

jobs:
  test-pypi:
    name: Test PyPi release
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # IMPORTANT: this permission is mandatory for trusted publishing
    steps:
      - name: Set up python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"

      - name: Upgrade pip
        run: python -m pip install --upgrade pip build

      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Create tag
        # if present, remove leading `v`
        run: |
          echo "NEBARI_TAG=$(git describe --tags | sed 's/^v//')" >> $GITHUB_ENV
          echo ${{ env.NEBARI_TAG }}

      - name: Build source and binary
        run: python -m build --sdist --wheel .

      - name: Publish to test PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: https://test.pypi.org/legacy/

      - name: Sleep
        run: sleep 120

      - name: Test install from Test PyPI
        run: |
          pip install \
          --index-url https://test.pypi.org/simple/ \
          --extra-index-url https://pypi.org/simple \
          nebari==${{ env.NEBARI_TAG }}

  release-pypi:
    name: Publish Nebari on PyPi
    runs-on: ubuntu-latest
    needs: test-pypi
    permissions:
      id-token: write
      contents: read

    steps:
      - name: Set up python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"

      - name: Upgrade pip
        run: python -m pip install --upgrade pip build

      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Build source and binary
        run: python -m build --sdist --wheel .

      - name: Publish package
        uses: pypa/gh-action-pypi-publish@release/v1
