name: Publish Crate

on:
  push:
    tags:
      - "v*"

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v6

      - name: Install libdbus-1-dev
        run: sudo apt-get update && sudo apt-get install -y libdbus-1-dev pkg-config

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Verify tag matches package version
        shell: bash
        run: |
          TAG_VERSION="${GITHUB_REF_NAME#v}"
          CARGO_VERSION="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1)"

          if [[ -z "$CARGO_VERSION" ]]; then
            echo "Could not determine package version from Cargo.toml"
            exit 1
          fi

          if [[ "$TAG_VERSION" != "$CARGO_VERSION" ]]; then
            echo "Tag version ($TAG_VERSION) does not match Cargo.toml version ($CARGO_VERSION)"
            exit 1
          fi

      - name: Dry run publish
        run: cargo publish --dry-run --locked

      - name: Publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish --locked
