name: Publish Crate

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:

permissions:
  contents: read

env:
  CRATE_NAME: feishu-sdk

jobs:
  version-info:
    name: Check Version
    runs-on: ubuntu-latest
    outputs:
      next_version: ${{ steps.version.outputs.next_version }}
      prev_version: ${{ steps.version.outputs.prev_version }}
      should_publish: ${{ steps.compare.outputs.should_publish }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Read local and published versions
        id: version
        shell: bash
        run: |
          set -euo pipefail
          next_version="$(sed -nE 's/^\s*version\s*=\s*"(.*)"/\1/p' Cargo.toml | head -n 1)"
          prev_version="$(cargo search "${CRATE_NAME}" --limit 1 | sed -nE 's/^[^"]*"([^"]+)".*/\1/p')"
          echo "next_version=${next_version}" >> "${GITHUB_OUTPUT}"
          echo "prev_version=${prev_version}" >> "${GITHUB_OUTPUT}"
          echo "next version: ${next_version}"
          echo "published version: ${prev_version:-<none>}"

      - name: Validate tag version matches Cargo.toml
        if: startsWith(github.ref, 'refs/tags/v')
        shell: bash
        run: |
          set -euo pipefail
          tag_version="${GITHUB_REF_NAME#v}"
          cargo_version="${{ steps.version.outputs.next_version }}"
          if [ "${tag_version}" != "${cargo_version}" ]; then
            echo "tag version (${tag_version}) does not match Cargo.toml (${cargo_version})"
            exit 1
          fi

      - name: Decide whether publishing is needed
        id: compare
        shell: bash
        run: |
          set -euo pipefail
          if [ -z "${{ steps.version.outputs.prev_version }}" ] || [ "${{ steps.version.outputs.next_version }}" != "${{ steps.version.outputs.prev_version }}" ]; then
            echo "should_publish=true" >> "${GITHUB_OUTPUT}"
            echo "publish required"
          else
            echo "should_publish=false" >> "${GITHUB_OUTPUT}"
            echo "same version on crates.io, skipping publish"
          fi

  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    needs: version-info
    if: needs.version-info.outputs.should_publish == 'true'

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Cargo login
        run: cargo login "${{ secrets.CRATES_TOKEN || secrets.CARGO_REGISTRY_TOKEN }}"

      - name: Cargo package
        run: cargo package --locked -p "${{ env.CRATE_NAME }}"

      - name: Publish crate
        run: cargo publish --locked -p "${{ env.CRATE_NAME }}"
