name: Linux CI (Rust)

on:
  push:
    branches:
      - linux/rust
    tags:
      - 'linux-v*'
    paths:
      - 'linux-rust/**'
      - '.github/workflows/linux-build.yml'
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y pkg-config libdbus-1-dev libpulse-dev appstream just libfuse2

      - name: Install AppImage tools
        run: |
          wget -q https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage -O /usr/local/bin/appimagetool
          wget -q https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage -O /usr/local/bin/linuxdeploy
          chmod +x /usr/local/bin/{appimagetool,linuxdeploy}

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Cache Cargo
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            linux-rust/target
          key: ${{ runner.os }}-cargo-${{ hashFiles('linux-rust/Cargo.lock') }}

      - name: Build AppImage and Binary
        working-directory: linux-rust
        run: |
          cargo build --release --verbose
          just
          mkdir -p dist
          cp target/release/librepods dist/librepods
          mv dist/LibrePods-x86_64.AppImage dist/librepods-x86_64.AppImage

      - name: Upload AppImage artifact
        if: "!startsWith(github.ref, 'refs/tags/linux-v')"
        uses: actions/upload-artifact@v4
        with:
          name: librepods-x86_64.AppImage
          path: linux-rust/dist/librepods-x86_64.AppImage

      - name: Upload binary artifact
        if: "!startsWith(github.ref, 'refs/tags/linux-v')"
        uses: actions/upload-artifact@v4
        with:
          name: librepods
          path: linux-rust/dist/librepods

      - name: Create tarball for Flatpak
        if: startsWith(github.ref, 'refs/tags/linux-v')
        working-directory: linux-rust
        run: |
          VERSION="${GITHUB_REF_NAME#linux-v}"
          just tarball "${VERSION}"
          echo "VERSION=${VERSION}" >> $GITHUB_ENV
          echo "TAR_PATH=linux-rust/dist/librepods-v${VERSION}-source.tar.gz" >> $GITHUB_ENV

      - name: Create GitHub Release (AppImage + binary + source)
        if: startsWith(github.ref, 'refs/tags/linux-v')
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          files: |
            linux-rust/dist/librepods-v${{ env.VERSION }}-source.tar.gz
            linux-rust/dist/librepods-x86_64.AppImage
            linux-rust/dist/librepods
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
