# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: "Setup Rust Environment"
description: "Setup Rust development environment with caching for RustFS"

inputs:
  rust-version:
    description: "Rust version to install"
    required: false
    default: "stable"
  cache-shared-key:
    description: "Shared cache key for Rust dependencies"
    required: false
    default: "rustfs-deps"
  cache-save-if:
    description: "Condition for saving cache"
    required: false
    default: "true"
  install-cross-tools:
    description: "Install cross-compilation tools"
    required: false
    default: "false"
  target:
    description: "Target architecture to add"
    required: false
    default: ""
  github-token:
    description: "GitHub token for API access"
    required: false
    default: ""

runs:
  using: "composite"
  steps:
    - name: Install system dependencies (Ubuntu)
      if: runner.os == 'Linux'
      shell: bash
      run: |
        sudo apt-get update
        sudo apt-get install -y \
          musl-tools \
          build-essential \
          lld \
          libdbus-1-dev \
          libwayland-dev \
          libwebkit2gtk-4.1-dev \
          libxdo-dev \
          pkg-config \
          libssl-dev

    - name: Install protoc
      uses: arduino/setup-protoc@v3
      with:
        version: "31.1"
        repo-token: ${{ inputs.github-token }}

    - name: Install flatc
      uses: Nugine/setup-flatc@v1
      with:
        version: "25.2.10"

    - name: Install Rust toolchain
      uses: dtolnay/rust-toolchain@stable
      with:
        toolchain: ${{ inputs.rust-version }}
        targets: ${{ inputs.target }}
        components: rustfmt, clippy

    - name: Install Zig
      if: inputs.install-cross-tools == 'true'
      uses: mlugg/setup-zig@v2

    - name: Install cargo-zigbuild
      if: inputs.install-cross-tools == 'true'
      uses: taiki-e/install-action@cargo-zigbuild

    - name: Install cargo-nextest
      uses: taiki-e/install-action@cargo-nextest

    - name: Setup Rust cache
      uses: Swatinem/rust-cache@v2
      with:
        cache-all-crates: true
        cache-on-failure: true
        shared-key: ${{ inputs.cache-shared-key }}
        save-if: ${{ inputs.cache-save-if }}
