name: Publish to crates.io

on:
  workflow_run:
    workflows: ["Release"]
    types:
      - completed

concurrency:
  group: publish-crates
  cancel-in-progress: false

jobs:
  publish:
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.workflow_run.head_commit.id }}

      - uses: dtolnay/rust-toolchain@stable

      - name: Check if version already published
        run: |
          VERSION=$(grep '^version ' Cargo.toml | head -1 | cut -d'"' -f2)
          HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
            "https://crates.io/api/v1/crates/leenfetch/${VERSION}")
          if [ "$HTTP_CODE" = "200" ]; then
            echo "Version ${VERSION} already published on crates.io. Skipping."
            exit 0
          fi
          echo "VERSION=${VERSION}" >> $GITHUB_ENV
          echo "Version ${VERSION} not found on crates.io. Proceeding."

      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_API_KEY }}
        run: cargo publish
