name: Auto Tag

on:
  push:
    branches:
      - main

jobs:
  tag:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get latest tag
        id: get_tag
        run: |
          git fetch --tags
          latest_tag=$(git tag --list 'v*' --sort=-v:refname | head -n 1)
          echo "latest_tag=$latest_tag" >> $GITHUB_OUTPUT

      - name: Bump version and create tag
        id: bump_tag
        run: |
          latest_tag="${{ steps.get_tag.outputs.latest_tag }}"
          if [ -z "$latest_tag" ]; then
            new_tag="v0.1.0"
          else
            IFS='.' read -r major minor patch <<<"${latest_tag#v}"
            patch=$((patch + 1))
            new_tag="v${major}.${minor}.${patch}"
          fi
          echo "new_tag=$new_tag" >> $GITHUB_OUTPUT
          git tag "$new_tag"
          git push origin "$new_tag"

      - name: Show new tag
        run: echo "Created tag ${{ steps.bump_tag.outputs.new_tag }}"
