name: Release
on:
  workflow_run:
    workflows: ["Test the package"]
    branches: [main]
    types: [completed]
  workflow_dispatch:

jobs:
  check-version:
    name: Check version and create release
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Extract version from Cargo.toml
        id: version
        run: |
          VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          echo "version=v$VERSION" >> $GITHUB_OUTPUT
          echo "Version: v$VERSION"

      - name: Check if tag exists
        id: check_tag
        run: |
          if git rev-parse "${{ steps.version.outputs.version }}" >/dev/null 2>&1; then
            echo "exists=true" >> $GITHUB_OUTPUT
          else
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Create tag
        if: steps.check_tag.outputs.exists == 'false'
        run: |
          git config user.name github-actions
          git config user.email github-actions@github.com
          git tag ${{ steps.version.outputs.version }}
          git push origin ${{ steps.version.outputs.version }}

      - name: Create GitHub Release
        if: steps.check_tag.outputs.exists == 'false'
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.version.outputs.version }}
          name: Release ${{ steps.version.outputs.version }}
          draft: false
          prerelease: false
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Install Rust
        if: steps.check_tag.outputs.exists == 'false'
        uses: dtolnay/rust-toolchain@stable

      - name: Install R
        if: steps.check_tag.outputs.exists == 'false'
        id: setup-r
        uses: r-lib/actions/setup-r@v2

      - name: Install R shared library
        if: steps.check_tag.outputs.exists == 'false'
        run: |
          sudo apt-get update -y
          sudo apt-get install -y r-base-dev
          echo "LIBRARY_PATH=/usr/lib/R/lib:$LIBRARY_PATH" >> $GITHUB_ENV
          echo "LD_LIBRARY_PATH=/usr/lib/R/lib:$LD_LIBRARY_PATH" >> $GITHUB_ENV

      - name: Publish to crates.io
        if: steps.check_tag.outputs.exists == 'false'
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
          LD_LIBRARY_PATH: ${{ steps.setup-r.outputs.r-home }}/lib
        run: cargo publish --features single-cell,multi-modal,gpu
