name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        
      - name: Check version match
        run: |
          CARGO_VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
          TAG_VERSION=${GITHUB_REF_NAME#v}
          if [ "$CARGO_VERSION" != "$TAG_VERSION" ]; then
            echo "::error::Version mismatch: Cargo.toml=$CARGO_VERSION, tag=$TAG_VERSION"
            exit 1
          fi
    
  build:
    needs: check
    strategy:
      matrix:
        include:
          - os: ubuntu-latest                                                                                             
            artifact: skl-linux
            binary: target/release/skl
          - os: macos-latest                                                                                              
            artifact: skl-macos
            binary: target/release/skl                                                                                    
          - os: windows-latest
            artifact: skl-windows
            binary: target/release/skl.exe
          
    runs-on: ${{ matrix.os }}
    
    steps:
      - name: Checkout
        uses: actions/checkout@v4
            
      - name: Cargo build
        run: cargo build --release

      - name: Rename binary
        shell: bash
        run: cp ${{ matrix.binary }} target/release/${{ matrix.artifact }}

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact }}
          path: target/release/${{ matrix.artifact }}
  
  publish:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write
    
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Cargo publish
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

      - name: Download artifacts
        uses: actions/download-artifact@v4                                                                                
        with:   
          path: artifacts

      - name: GitHub release
        uses: softprops/action-gh-release@v2
        with:                                                                                                             
          files: |
            artifacts/skl-linux/skl-linux
            artifacts/skl-macos/skl-macos
            artifacts/skl-windows/skl-windows
