# syntax=docker/dockerfile:1.7

# Build stage — compiles the `picloud` all-in-one binary against the
# pinned toolchain from rust-toolchain.toml.
FROM rust:1.92-slim-bookworm AS builder

WORKDIR /build

# System libs needed for the build (sqlx + reqwest pull rustls so we
# don't need OpenSSL; pkg-config still helps a few transitive crates).
RUN apt-get update \
	&& apt-get install -y --no-install-recommends pkg-config \
	&& rm -rf /var/lib/apt/lists/*

# Copy the workspace. We could split deps from sources with cargo-chef
# for better layer caching; defer that until build times become a
# bottleneck — current cold build is well under a minute on a laptop.
COPY rust-toolchain.toml Cargo.toml Cargo.lock ./
COPY crates ./crates

RUN --mount=type=cache,target=/usr/local/cargo/registry \
	--mount=type=cache,target=/build/target \
	cargo build --release --bin picloud \
	&& cp target/release/picloud /tmp/picloud

# Runtime stage — debian-slim is ~30MB and has the CA bundle we need
# for outbound HTTPS in v1.1+.
FROM debian:bookworm-slim AS runtime

RUN apt-get update \
	&& apt-get install -y --no-install-recommends ca-certificates curl \
	&& rm -rf /var/lib/apt/lists/* \
	&& useradd --create-home --shell /usr/sbin/nologin --uid 10001 picloud

COPY --from=builder /tmp/picloud /usr/local/bin/picloud

USER picloud
WORKDIR /home/picloud

ENV PICLOUD_BIND=0.0.0.0:8080 \
	RUST_LOG=info

EXPOSE 8080

HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --retries=3 \
	CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1

ENTRYPOINT ["/usr/local/bin/picloud"]
