name: Publish Crate

on:
  push:
    tags:
      - "v*"

permissions: read-all

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    name: Publish to crates.io
    if: ${{ !contains(github.ref_name, '-') }}
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10  # 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@193d6aa1dbbc28bd2c0a6b0e327cfdce68baaf6e  # stable

      - uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4  # 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
