# Build. rusqlite is bundled (compiles SQLite from source) and librqbit needs a C
# toolchain, so the builder needs cc. TLS is rustls throughout, so no OpenSSL headers.
# build.rs builds the web pages from TypeScript with swc, which needs node.
FROM rust:1-slim-bookworm AS build
RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential nodejs npm \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /src

# swc only: Playwright and TypeScript are for testing and type-checking, not for building.
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

# Dependencies first, so editing the source does not rebuild librqbit every time.
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo 'fn main(){}' > src/main.rs \
    && cargo build --release --locked \
    && rm -rf src

COPY build.rs ./
COPY src ./src
COPY web ./web
# cargo skips a rebuild if mtimes look untouched; make sure it does not.
RUN touch src/main.rs && cargo build --release --locked

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates gosu \
    && rm -rf /var/lib/apt/lists/*
COPY --from=build /src/target/release/ipx /usr/local/bin/ipx
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

ENV IPX_CONFIG=/config/config.toml \
    IPX_DATA_DIR=/data \
    IPX_LOG=ipx=info \
    PUID=99 \
    PGID=100
VOLUME ["/config", "/data", "/downloads"]

# Web UI, and the BitTorrent peer port (TCP and UDP -- DHT needs the UDP side).
EXPOSE 8099/tcp 6881/tcp 6881/udp

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["ipx", "daemon"]
