name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:

    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@v4

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

    - name: Install & upgrade Python build tools
      run: |
        python -m pip install --upgrade pip setuptools

    - name: Build package
      run: |
        python setup.py install

    - name: Get versions into environment
      run: |
        VERSION=$(python setup.py --version)
        TAG_VERSION=${GITHUB_REF##*/v}
        TAG_FULL=${GITHUB_REF##*/}
        echo "setup_version=$VERSION" >> $GITHUB_ENV
        echo "tag_version=$TAG_VERSION" >> $GITHUB_ENV
        echo "tag_full=$TAG_FULL" >> $GITHUB_ENV

    - name: Compare versions and report
      run: |
        echo "setup.py version: ${{ env.setup_version }}"
        echo "Latest tag version: ${{ env.tag_version }}"
        if [[ ${{ env.setup_version }} != ${{ env.tag_version }} ]]; then
          echo "Versions are not identical -> quitting workflow."
          exit 23
        else
          echo "OK, versions match -> creating release."
          exit 0
        fi

    - name: "Get latest release"
      id: last_release
      uses: InsonusK/get-latest-release@v1.0.1
      with:
        myToken: ${{ secrets.GITHUB_TOKEN }}
        exclude_types: ""
        view_top: 1

    - name: "Print latest release results"
      run: |
        echo "id: ${{ steps.last_release.outputs.id }}"
        echo "name: ${{ steps.last_release.outputs.name }}"
        echo "tag_name: ${{ steps.last_release.outputs.tag_name }}"
        echo "created_at: ${{ steps.last_release.outputs.created_atd }}"
        echo "draft: ${{ steps.last_release.outputs.draft }}"
        echo "prerelease: ${{ steps.last_release.outputs.prerelease }}"

    - name: "Check if release is existing"
      id: check
      run: |
        if [[ "${{ steps.last_release.outputs.tag_name }}" == "${{ env.tag_full }}" ]];
        then
          echo "::set-output name=release_existing::true"
        else
          echo "::set-output name=release_existing::false"
        fi

    - name: Create release
      id: create_release
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        tag_name: v${{ env.tag_version }}
        release_name: v${{ env.tag_version }}
        body: |
          This is an autogenerated ${{ github.repository }} release.
          Release notes coming soon...
          ## Improved / Changed
          ## New
          ## Fixed
          ## Notes
        draft: false
        prerelease: false
      if: ${{ steps.check.outputs.release_existing == 'false' }}

