name: Publish Rust Crate by Tag

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

jobs:
  publish:
    permissions:
      contents: read

    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt install libasound2-dev

      - name: Extract crate prefix and version from tag
        id: extract
        run: |
          TAG_NAME=${GITHUB_REF#refs/tags/}
          if [[ "$TAG_NAME" =~ ^v[0-9].* ]]; then
            # Handle tags like "v0.7.2"
            PREFIX="trnovel"
            VERSION=$(echo "$TAG_NAME" | sed -E 's/v([0-9].*)/\1/')
          else
            # Handle tags like "parse-book-source-v0.1.6"
            PREFIX=$(echo "$TAG_NAME" | sed -E 's/(.*)-v[0-9].*/\1/')
            VERSION=$(echo "$TAG_NAME" | sed -E 's/.*-v([0-9].*)/\1/')
          fi
          echo $PREFIX
          echo $VERSION
          echo "prefix=$PREFIX" >> $GITHUB_OUTPUT
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Publish crate
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: |
          # 根据前缀确定路径
          if [ ${{steps.extract.outputs.prefix}} = "parse-book-source" ] || [ ${{steps.extract.outputs.prefix}} = "novel-tts" ]; then
            CRATE_PATH="crates/${{steps.extract.outputs.prefix}}"
          else
            CRATE_PATH="./"
          fi

          if [ ! -f "$CRATE_PATH/Cargo.toml" ]; then
            echo "Crate path $CRATE_PATH not found!" && exit 1
          fi

          cd "$CRATE_PATH"
          ls
          cargo publish --token "$CARGO_REGISTRY_TOKEN"
