# Stage 1: build web API
FROM golang:1.26-alpine AS web-builder
WORKDIR /src
COPY web/go.mod web/go.sum ./
RUN go mod download
COPY web/*.go web/index.html ./
RUN CGO_ENABLED=0 go build -o /server .

# Stage 2: build worker binary
FROM golang:1.26-alpine AS worker-builder
WORKDIR /src
COPY worker/go.mod worker/go.sum ./
RUN go mod download
COPY worker/*.go ./
RUN CGO_ENABLED=0 go build -o /worker .

# Stage 3: build vtracer from Rust
FROM rust:1-slim AS rust-builder
RUN cargo install vtracer

# Stage 4: download inkstitch
FROM debian:trixie-slim AS inkstitch-builder
RUN apt-get update && apt-get install -y --no-install-recommends \
    wget xz-utils ca-certificates \
    && rm -rf /var/lib/apt/lists/*
ARG INKSTITCH_VERSION=3.2.2
RUN ARCH=$(dpkg --print-architecture) && \
    if [ "$ARCH" = "arm64" ]; then INKARCH="aarch64"; else INKARCH="x86_64"; fi && \
    wget -q "https://github.com/inkstitch/inkstitch/releases/download/v${INKSTITCH_VERSION}/inkstitch-${INKSTITCH_VERSION}-linux-${INKARCH}.tar.xz" \
    -O /tmp/inkstitch.tar.xz && \
    mkdir -p /opt/inkstitch && \
    tar xJf /tmp/inkstitch.tar.xz -C /opt/inkstitch && \
    rm /tmp/inkstitch.tar.xz && \
    rm -rf /opt/inkstitch/inkstitch/fonts \
           /opt/inkstitch/inkstitch/bin/locales \
           /opt/inkstitch/inkstitch/inx \
           /opt/inkstitch/inkstitch/palettes \
           /opt/inkstitch/inkstitch/tiles \
           /opt/inkstitch/inkstitch/addons \
           /opt/inkstitch/inkstitch/symbols \
           /opt/inkstitch/inkstitch/dbus

# Stage 5: runtime
FROM debian:trixie-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
    inkscape libwayland-cursor0 libdrm2 libgbm1 libxcb-dri3-0 \
    && rm -rf /var/lib/apt/lists/*

COPY --from=web-builder /server /usr/local/bin/server
COPY --from=worker-builder /worker /usr/local/bin/worker
COPY --from=rust-builder /usr/local/cargo/bin/vtracer /usr/local/bin/vtracer
COPY --from=inkstitch-builder /opt/inkstitch /opt/inkstitch
ENV INKSTITCH_BIN=/opt/inkstitch/inkstitch/bin/inkstitch
