name: Desktop Build

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  workflow_dispatch:

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact_name: tinyfiledialogs-linux
            packages: libgtk-3-dev
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            artifact_name: tinyfiledialogs-windows
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact_name: tinyfiledialogs-macos

    runs-on: ${{ matrix.os }}
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}
          components: clippy
      
      - name: Install Linux dependencies
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y ${{ matrix.packages }}
      
      - name: Cache Rust dependencies
        uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}
      
      - name: Build
        run: cargo build --release --target ${{ matrix.target }}
      
      - name: Run tests
        run: cargo test --target ${{ matrix.target }}
      
      - name: Build example
        run: cargo build --release --example test --target ${{ matrix.target }}
      
      - name: Package artifacts
        shell: bash
        run: |
          mkdir -p artifacts
          if [ "${{ matrix.os }}" = "windows-latest" ]; then
            cp target/${{ matrix.target }}/release/examples/test.exe artifacts/tinyfiledialogs-example.exe
            cp target/${{ matrix.target }}/release/libtinyfiledialogs.rlib artifacts/
          else
            cp target/${{ matrix.target }}/release/examples/test artifacts/tinyfiledialogs-example
            cp target/${{ matrix.target }}/release/libtinyfiledialogs.rlib artifacts/
          fi
      
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact_name }}
          path: artifacts/
  
  release:
    needs: build
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Download all artifacts
        uses: actions/download-artifact@v3
        with:
          path: all-artifacts
      
      - name: Create release
        uses: softprops/action-gh-release@v1
        with:
          files: all-artifacts/**/*
          draft: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}