# veiled-server container image.
#
# Multi stage: a musl build with `crt-static` so the final binary is a single static executable
# (no GLIBC, no OpenSSL, SQLite is bundled inside it), then a small Alpine runtime with a non-root
# user and a /data volume.
#
# Build with the repository root as the context. A .dockerignore at the repository root that
# drops target/, desktop/ and client/node_modules keeps the context small; without one the whole
# working tree is uploaded, which still works but is slow.
#
#   docker build -f server/Dockerfile -t veiled-server .
#   docker run -d --name veiled -p 8443:8443 -p 8444:8444/udp -v veiled-data:/data veiled-server
#   curl -k https://127.0.0.1:8443/health
#
# The built web client can be served from the same container by mounting it read only:
#   -v "$PWD/client/dist:/usr/share/veiled/client:ro"
#
# Environment:
#   VEILED_CONFIG          config file path inside the container (default /data/veiled.toml)
#   VEILED_NAME            server name used when the config is created on first start
#   VEILED_JOIN_PASSWORD   join password used on first start, empty means an open server
#   VEILED_ADMIN_PASSWORD  admin password used on first start
#   VEILED_CLIENT_DIR      directory served as the static client (default /usr/share/veiled/client)

FROM rust:1-slim-bookworm AS build
RUN apt-get update \
    && apt-get install -y --no-install-recommends musl-tools binutils file gcc ca-certificates \
    && rm -rf /var/lib/apt/lists/*
RUN rustup target add x86_64-unknown-linux-musl
WORKDIR /src

COPY Cargo.toml ./
COPY core ./core
COPY server ./server
# This image builds core and server only. The workspace manifest is trimmed in the image copy so
# the build does not depend on crates that are not part of the server image (tools/bench lives in
# another workstream and desktop is excluded from the workspace anyway).
RUN sed -i -E 's#^members = \[.*\]#members = ["core", "server"]#' Cargo.toml \
    && grep -n '^members' Cargo.toml

ENV RUSTFLAGS="-C target-feature=+crt-static"
ENV CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-C target-feature=+crt-static"
RUN cargo build --release --target x86_64-unknown-linux-musl -p veiled-server \
    && file /src/target/x86_64-unknown-linux-musl/release/veiled-server \
    && strip /src/target/x86_64-unknown-linux-musl/release/veiled-server

FROM alpine:3.20
RUN addgroup -S -g 10001 veiled \
    && adduser -S -D -H -u 10001 -G veiled veiled \
    && mkdir -p /data /usr/share/veiled/client \
    && chown -R veiled:veiled /data /usr/share/veiled
COPY --from=build /src/target/x86_64-unknown-linux-musl/release/veiled-server /usr/local/bin/veiled-server
COPY server/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod 0755 /usr/local/bin/veiled-server /usr/local/bin/docker-entrypoint.sh

USER veiled
WORKDIR /data
VOLUME ["/data"]
EXPOSE 8443/tcp
EXPOSE 8444/udp

ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
CMD ["run"]
