name: Publish to crates.io

on:
  release:
    types: [published]

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          token: ${{ secrets.PAT_TOKEN }}

      - name: Extract version from tag
        id: version
        run: |
          VERSION=${GITHUB_REF_NAME#v}
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Install system dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libwayland-dev libxkbcommon-dev

      - name: Install cargo-release
        uses: taiki-e/install-action@v2
        with:
          tool: cargo-release

      - name: Set version
        run: cargo release version ${{ steps.version.outputs.version }} --execute --no-confirm

      - name: Commit version bump
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add -A
          git commit -m "chore: bump version to ${{ steps.version.outputs.version }}"
          git push origin HEAD:main

      - name: Publish workspace
        run: cargo release publish --workspace --execute --no-confirm --allow-branch HEAD
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
