name: Release

on:
  push:
    branches:
      - master

jobs:
  check_for_changed_version:
    runs-on: 'ubuntu-latest'
    # Declare outputs for next jobs
    outputs:
      version_changed: ${{ steps.check_file_changed.outputs.version_changed }}
    steps:
    - uses: actions/checkout@v2
      with:
        # Checkout as many commits as needed for the diff
        fetch-depth: 2
    - id: check_file_changed
      run: |
        # Diff HEAD with the previous commit
        if git diff HEAD^ HEAD pyproject.toml | grep -q "+version =";
        then
          GOTIME="True"
        else
          GOTIME="False"
        fi
        echo "::notice title=GOTIME::$GOTIME"
        # Set the output named "version_changed"
        echo "version_changed=$GOTIME" >> $GITHUB_OUTPUT

  build:
    runs-on: ubuntu-latest
    # this should start working with https://github.com/go-gitea/gitea/pull/24230
    # needs: [ check_for_changed_version ]
    # if: needs.check_for_changed_version.outputs.version_changed == 'True'
    permissions:
      contents: write
    steps:
    - uses: https://github.com/actions/checkout@v2
    - uses: https://github.com/actions/setup-python@v4
      with:
        python-version: '3.11.x'
    - name: Install Env
      # this should be all we need because shiv will download the deps itself
      run: |
        pip install --upgrade pip
        pip install shiv
        pip install poetry
    - name: Add VERSION env property
      run: |
        echo "VERSION=v$(poetry version | python -c 'import sys;print(sys.stdin.read().split()[1])')" >> $GITHUB_ENV
        echo ${{ env.VERSION }}
    - name: Build the sucker
      run: |
        sed -i -e "s/?????/${{ env.VERSION }}/g" src/__init__.py
        make build
    - name: Create release!
      run: |
        JSON_DATA=$(
          printf '%s' \
          '{'\
            '"tag_name":"${{ env.VERSION }}",'\
            '"name":"${{ env.VERSION }}",'\
            '"body":"RELEASE THE KRAKEN"'\
          '}' \
        )
        echo """release_id=$(\
          curl -X POST \
          -s https://git.joekaufeld.com/api/v1/repos/${GITHUB_REPOSITORY%/*}/${{ github.event.repository.name }}/releases \
          -H "Authorization: token ${{ secrets.PAT }}" \
          -H 'Content-Type: application/json' \
          -d "$JSON_DATA" \
          | python3 -c "import sys, json; print(json.load(sys.stdin)['id'])"\
        )""" >> $GITHUB_ENV
    - name: Upload assets!
      run: |
        curl https://git.joekaufeld.com/api/v1/repos/${GITHUB_REPOSITORY%/*}/${{ github.event.repository.name }}/releases/${{ env.release_id }}/assets \
        -H "Authorization: token ${{ secrets.PAT }}" \
        -F attachment=@utils