name: Auto Tag Develop

on:
  push:
    branches:
      - develop

jobs:
  tag:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.REGISTRY_TOKEN }}
          persist-credentials: true

      - name: Create next tag from config/version.yaml
        shell: bash
        run: |
          set -euo pipefail

          # Skip if current commit already has a vX.Y.Z tag
          if git tag --points-at HEAD | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
            echo "Tag already exists on this commit. Skipping."
            exit 0
          fi

          changed_version=false
          if git diff --name-only "${{ gitea.event.before }}" "${{ gitea.event.after }}" | grep -q '^config/version\.yaml$'; then
            changed_version=true
          fi

          read_version() {
            awk -F': *' '/app\.version:/{print $2}' config/version.yaml | tr -d '[:space:]' | tr -d "'\""
          }

          if $changed_version; then
            version="$(read_version)"
            if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
              echo "Invalid version in version.yaml: $version" >&2
              exit 1
            fi
          else
            last_tag="$(git tag -l 'v*' --sort=-v:refname | head -n1 || true)"
            if [ -z "$last_tag" ]; then
              version="0.1.0"
            else
              base="${last_tag#v}"
              IFS='.' read -r major minor patch <<< "$base"
              version="${major}.${minor}.$((patch + 1))"
            fi

            printf "parameters:\\n    app.version: '%s'\\n" "$version" > config/version.yaml
            git config user.name "gitea-actions"
            git config user.email "gitea-actions@local"
            git add config/version.yaml
            git commit -m "chore : bump version to v$version" || true
            git push origin develop || true
          fi

          tag="v$version"
          git tag "$tag"
          git push origin "$tag"
