name: Release

on:
  push:
    branches: [main, master]
    paths:
      - "Cargo.toml"
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

jobs:
  release:
    name: Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 2

      - name: Check if version changed
        id: version
        run: |
          OLD_VERSION=$(git show HEAD~1:Cargo.toml | grep '^version' | head -1 | sed 's/.*"\(.*\)".*/\1/')
          NEW_VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
          echo "old=$OLD_VERSION" >> $GITHUB_OUTPUT
          echo "new=$NEW_VERSION" >> $GITHUB_OUTPUT
          if [ "$OLD_VERSION" != "$NEW_VERSION" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Setup Rust
        if: steps.version.outputs.changed == 'true'
        uses: dtolnay/rust-toolchain@stable

      - name: Publish to crates.io
        if: steps.version.outputs.changed == 'true'
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

      - name: Create GitHub Release
        if: steps.version.outputs.changed == 'true'
        uses: softprops/action-gh-release@v2
        with:
          tag_name: v${{ steps.version.outputs.new }}
          name: v${{ steps.version.outputs.new }}
          generate_release_notes: true
          draft: false
          prerelease: false
