name: Update README version

on:
  release:
    types: [published]

permissions:
  contents: write

jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          ref: main
          token: ${{ secrets.ORG_DISPATCH_TOKEN }}

      - name: Update version in README
        run: |
          VERSION="${{ github.event.release.tag_name }}"
          FILE="README.md"

          # Update cargo dependency version (e.g. "0.2" -> "0.3")
          MAJOR_MINOR="${VERSION#v}"
          MAJOR_MINOR="${MAJOR_MINOR%.*}"
          sed -i "s|libfreemkv = \"[0-9]*\.[0-9]*\"|libfreemkv = \"${MAJOR_MINOR}\"|" "$FILE"

      - name: Commit and push
        run: |
          VERSION="${{ github.event.release.tag_name }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add README.md
          git diff --cached --quiet || git commit -m "Update to libfreemkv ${VERSION}"
          git push
