name: Auto Release

on:
  push:
    branches:
      - main
    paths:
      - 'Cargo.toml'
      - 'src/**'

permissions:
  contents: write

jobs:
  check-version:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get_version.outputs.version }}
      should_release: ${{ steps.check_tag.outputs.should_release }}

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get version from Cargo.toml
        id: get_version
        run: |
          VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Check if tag exists
        id: check_tag
        run: |
          if git rev-parse "v${{ steps.get_version.outputs.version }}" >/dev/null 2>&1; then
            echo "Tag v${{ steps.get_version.outputs.version }} already exists"
            echo "should_release=false" >> $GITHUB_OUTPUT
          else
            echo "Tag v${{ steps.get_version.outputs.version }} does not exist, will create release"
            echo "should_release=true" >> $GITHUB_OUTPUT
          fi

  create-tag:
    needs: check-version
    if: needs.check-version.outputs.should_release == 'true'
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Create and push tag
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a "v${{ needs.check-version.outputs.version }}" -m "Release v${{ needs.check-version.outputs.version }}"
          git push origin "v${{ needs.check-version.outputs.version }}"
