name: Rust

on:
  push:
    tags:
      - 'v*'

env:
  CARGO_TERM_COLOR: always

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    steps:
    - uses: actions/checkout@v4

    - name: Set up Rust
      uses: dtolnay/rust-toolchain@stable

    - uses: swatinem/rust-cache@v2

    - uses: rust-lang/crates-io-auth-action@v1
      id: auth

    # === バージョンチェック ===
    - name: Check version with cargo search
      id: check
      shell: bash
      run: |
        # 1. Cargo.toml から name と version を取得
        NAME=$(grep -m1 '^name =' Cargo.toml | cut -d '"' -f 2)
        VERSION=$(grep -m1 '^version =' Cargo.toml | cut -d '"' -f 2)
        
        echo "Checking logic for: $NAME = \"$VERSION\""

        # 2. crates.io を検索 (color=neverで色コード除去)
        SEARCH_RESULT=$(CARGO_TERM_COLOR=never cargo search "$NAME" --limit 1)
        
        # 3. 判定 (正規表現でスペースの揺れに対応: \s* = 任意の空白)
        # 行頭(^)から 名前、等号、バージョン が一致するか確認
        if echo "$SEARCH_RESULT" | grep -E -q "^$NAME\s*=\s*\"$VERSION\""; then
          echo "::notice::Version $VERSION is already published on crates.io. Skipping all subsequent steps."
          echo "should_publish=false" >> $GITHUB_OUTPUT
        else
          echo "::notice::Version $VERSION not found on crates.io. Proceeding."
          echo "should_publish=true" >> $GITHUB_OUTPUT
        fi

    # === 以下のステップすべてに if 条件を追加 ===

    - name: Run tests
      # 公開すべき時(true) かつ Pushの時だけ実行
      if: steps.check.outputs.should_publish == 'true' && github.event_name == 'push'
      run: cargo test --verbose

    - name: Publish
      # 公開すべき時(true) かつ Pushの時だけ実行
      if: steps.check.outputs.should_publish == 'true' && github.event_name == 'push'
      run: cargo publish
      env:
        CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
