name: ytld-sub Release
on:
  push:
    # publish only when pushed to master
    branches:
      - master
jobs:
  pypi-publish:
    name: pypi-publish
    runs-on: ubuntu-22.04
    strategy:
      matrix:
        python-version: [ "3.10" ]

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0  # Needed for correct commit count. TODO: define once using GH actions
          ref: master

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v3
        with:
          python-version: ${{ matrix.python-version }}

      - name: Build Wheel
        run: |
          make wheel

      - name: Publish distribution 📦 to PyPI
        if: ${{ github.ref == 'refs/heads/master' }}
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          password: ${{ secrets.PYPI_API_TOKEN }}

  github-release:
    name: github-release
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
          ref: master  # Needed for correct commit count. TODO: define once using GH actions

      - name: Set version envs 1/3
        run: |
          echo "DATE=$(date +'%Y.%m.%d')" >> $GITHUB_ENV
          echo "COMMIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV

      - name: Set version envs 2/3
        run: |
          echo "DATE_COMMIT_COUNT=$(git rev-list --count master --since='${{ env.DATE }} 00:00:00')" >> $GITHUB_ENV

      - name: Set version envs 3/3
        run: |
          echo "LOCAL_VERSION=${{ env.DATE }}+${{ env.COMMIT_HASH }}" >> $GITHUB_ENV
          if [ ${{ env.COMMIT_HASH }} = "0" ]
          then
            echo "PYPI_VERSION=${{ env.DATE }}" >> $GITHUB_ENV
          else
            echo "PYPI_VERSION=${{ env.DATE }}.post${{ env.DATE_COMMIT_COUNT }}" >> $GITHUB_ENV
          fi

      - name: Test version envs
        run: |
          echo "${{ env.PYPI_VERSION }}"
          echo "${{ env.LOCAL_VERSION }}"

      - name: Create Release
        if: ${{ github.ref == 'refs/heads/master' }}
        id: create_release
        uses: softprops/action-gh-release@v1
        with:
          name: ytdl-sub ${{ env.PYPI_VERSION }}
          tag_name: ${{ env.PYPI_VERSION }}
          body: |
            See https://github.com/jmbannon/ytdl-sub#installation for installation steps
          draft: false
          prerelease: false