# syntax=docker/dockerfile:1

# ── Chef (installs cargo-chef once, reused by planner + builder) ───────────────
FROM rust:1.96-bookworm AS chef
RUN cargo install cargo-chef --locked
WORKDIR /build

# ── Planner: compute dependency recipe from manifest ──────────────────────────
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json

# ── Builder: cook deps (cached), then build binary ───────────────────────────
FROM chef AS builder

RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    apt-get update && apt-get install -y --no-install-recommends \
        pkg-config libssl-dev lld

ENV RUSTFLAGS="-C link-arg=-fuse-ld=lld"

# Cook deps — this layer is cached as long as Cargo.toml/Cargo.lock are unchanged
COPY --from=planner /build/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json

# Build binary — only reruns when src/ or config changes
COPY . .
RUN cargo build --release --bin flaresolverr-rs

# ── Runtime ────────────────────────────────────────────────────────────────────
FROM debian:bookworm-slim AS runtime

RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
        wget gnupg ca-certificates libssl3 \
        fonts-liberation libnss3 libatk1.0-0 libatk-bridge2.0-0 \
        libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
        libxrandr2 libgbm1 libasound2 xvfb \
    && wget -qO- https://dl.google.com/linux/linux_signing_key.pub \
       | gpg --dearmor > /usr/share/keyrings/google-chrome.gpg \
    && echo "deb [arch=amd64 signed-by=/usr/share/keyrings/google-chrome.gpg] \
       http://dl.google.com/linux/chrome/deb/ stable main" \
       > /etc/apt/sources.list.d/google-chrome.list \
    && apt-get update && apt-get install -y --no-install-recommends google-chrome-stable

WORKDIR /app
COPY --from=builder /build/target/release/flaresolverr-rs ./
COPY config.toml ./

RUN sed -i 's/^headless\s*=.*/headless        = false/' config.toml \
 && sed -i 's/^virtual_display\s*=.*/virtual_display = true/' config.toml

EXPOSE 8191
CMD ["./flaresolverr-rs"]
