name: build-mailadler-linux

on:
  workflow_dispatch:
  push:
    branches: [main, master]
    paths:
      - 'src/**'
      - 'CMakeLists.txt'
      - '.github/workflows/build-linux.yml'
  pull_request:
    branches: [main, master]

env:
  QT_VERSION: 6.6.3

jobs:
  build:
    runs-on: ubuntu-22.04

    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Install Qt
        uses: jurplel/install-qt-action@v4
        with:
          version: ${{ env.QT_VERSION }}
          modules: 'qtwebsockets'
          cache: true

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            build-essential \
            cmake \
            ninja-build \
            libgl1-mesa-dev \
            libxkbcommon-dev \
            libxcb-xinerama0-dev \
            libxcb-cursor0 \
            libsqlite3-dev \
            libssl-dev \
            desktop-file-utils \
            libfuse2 \
            imagemagick

      - name: Prepare version
        run: |
          VERSION=$(date +"%y.%-m.%-d-%H%M")
          echo "VERSION=$VERSION" >> $GITHUB_ENV

      - name: Configure
        run: |
          cmake -B build -G Ninja \
            -DCMAKE_BUILD_TYPE=Release \
            -DCMAKE_INSTALL_PREFIX=/usr

      - name: Build
        run: cmake --build build --parallel

      - name: Package portable
        run: |
          cd build
          DESTDIR=../mailadler-portable cmake --install .
          cd ..
          tar -cJf mailadler-linux-x86_64-${{ env.VERSION }}.txz mailadler-portable

      - name: Upload portable artifact
        uses: actions/upload-artifact@v4
        with:
          name: linux-portable
          path: mailadler-linux-x86_64-*.txz

      - name: Package AppImage
        run: |
          mkdir -p packaging/linux/mailadler
          echo "${{ env.VERSION }}" > packaging/linux/mailadler/VERSION
          cd packaging/linux
          export PKG2AICOMMIT=1eceb306077e51b991e987690b364e11971b44b3
          wget -q https://raw.githubusercontent.com/probonopd/AppImages/${PKG2AICOMMIT}/pkg2appimage || true
          if [ -f pkg2appimage ] && [ -f appimage/appimage.yml ]; then
            bash -ex pkg2appimage appimage/appimage.yml
            mv out/*.AppImage out/mailadler-linux-x86_64-${{ env.VERSION }}.AppImage 2>/dev/null || echo "AppImage packaging skipped"
          else
            echo "AppImage packaging not configured yet"
          fi

      - name: Upload AppImage artifact
        if: success()
        uses: actions/upload-artifact@v4
        with:
          name: linux-appimage
          path: packaging/linux/out/*.AppImage
          if-no-files-found: ignore

      - name: Upload to release (on tag)
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v1
        with:
          files: |
            mailadler-linux-x86_64-*.txz
            packaging/linux/out/*.AppImage
