name: Publish

on:
  push:
    branches: [main]
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

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

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

      - name: Cache cargo dependencies
        uses: Swatinem/rust-cache@v2

      - name: Run checks
        run: |
          cargo check --all-features
          cargo test --all-features
          cargo clippy --all-features

      - name: Check if version changed
        id: version
        run: |
          LOCAL_VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
          echo "local=$LOCAL_VERSION" >> $GITHUB_OUTPUT

          # Get published version from crates.io
          REMOTE_VERSION=$(curl -s "https://crates.io/api/v1/crates/cockpit" | jq -r '.crate.max_version // "0.0.0"')
          echo "remote=$REMOTE_VERSION" >> $GITHUB_OUTPUT

          if [ "$LOCAL_VERSION" != "$REMOTE_VERSION" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
            echo "Version changed: $REMOTE_VERSION -> $LOCAL_VERSION"
          else
            echo "changed=false" >> $GITHUB_OUTPUT
            echo "Version unchanged: $LOCAL_VERSION"
          fi

      - name: Publish to crates.io
        if: steps.version.outputs.changed == 'true'
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
