# Publishes the crate to Crates.io for each new tag
name: 📦 Publish crates

on:
  workflow_dispatch:
  push:
    tags:
      - '*'

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    name: 📦 Publish
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - name: 🛎️ Checkout tag
        uses: actions/checkout@v6
        with:
          persist-credentials: false

      - name: 🦀 Setup Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: 🔍 Verify Cargo.toml version matches tag
        if: github.ref_type == 'tag'
        env:
          TAG: ${{ github.ref_name }}
        run: |
          set -euo pipefail
          VERSION=$(grep -m1 '^version' Cargo.toml | sed -E 's/.*"(.*)".*/\1/')
          if [ "$VERSION" != "$TAG" ]; then
            echo "::error::Cargo.toml version ($VERSION) does not match tag ($TAG)"
            exit 1
          fi
          echo "Publishing adguardian v$VERSION"

      - name: ✅ Run tests
        run: cargo test --locked

      - name: 📦 Publish to Crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
        run: cargo publish --locked
