FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

# Tauri v2 build dependencies for Ubuntu 24.04 (glibc 2.39, WebKitGTK 2.44+)
# Targets any distro from mid-2024 onwards while supporting modern Wayland compositors
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    wget \
    file \
    libgtk-3-dev \
    libwebkit2gtk-4.1-dev \
    librsvg2-dev \
    patchelf \
    libssl-dev \
    libayatana-appindicator3-dev \
    libglib2.0-dev \
    libgdk-pixbuf2.0-dev \
    libsoup-3.0-dev \
    libjavascriptcoregtk-4.1-dev \
    xdg-utils \
    && rm -rf /var/lib/apt/lists/*

# Install Node.js 22 LTS
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
    && apt-get install -y nodejs \
    && rm -rf /var/lib/apt/lists/*

# Install Rust stable
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
ENV PATH="/root/.cargo/bin:${PATH}"

WORKDIR /app

# Cache Rust dependencies first
COPY src-tauri/Cargo.toml src-tauri/Cargo.lock src-tauri/
COPY src-tauri/build.rs src-tauri/
# Create stub lib/main so cargo can resolve the crate
RUN mkdir -p src-tauri/src && \
    echo 'fn main() {}' > src-tauri/src/main.rs && \
    echo '' > src-tauri/src/lib.rs && \
    cd src-tauri && cargo fetch && \
    rm -rf src

# Cache npm dependencies
COPY package.json package-lock.json ./
RUN npm ci

# Copy the full source
COPY . .

# Build the AppImage
RUN npx tauri build --bundles appimage

# Strip GPU/GL libraries that linuxdeploy bundles from the build system.
# These MUST come from the host's GPU driver at runtime  - bundling them causes
# black windows, EGL failures, and driver mismatches on any system with a
# different Mesa version or proprietary NVIDIA drivers.
# See: https://github.com/AppImage/pkg2appimage/blob/master/excludelist
RUN cd src-tauri/target/release/bundle/appimage && \
    chmod +x *.AppImage && \
    ./*.AppImage --appimage-extract && \
    find squashfs-root \( \
        -name "libEGL.so*" -o \
        -name "libGL.so*" -o \
        -name "libGLX.so*" -o \
        -name "libGLdispatch.so*" -o \
        -name "libOpenGL.so*" -o \
        -name "libgbm.so*" -o \
        -name "libdrm.so*" -o \
        -name "libglapi.so*" -o \
        -name "libGLESv2.so*" \
    \) -delete && \
    rm -f *.AppImage && \
    wget -q https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage -O /tmp/appimagetool && \
    chmod +x /tmp/appimagetool && \
    ARCH=x86_64 /tmp/appimagetool --appimage-extract-and-run --no-appstream squashfs-root/ && \
    rm -rf squashfs-root /tmp/appimagetool

# The AppImage will be in src-tauri/target/release/bundle/appimage/
