# 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-trixie 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: each crate of
# the workspace as an empty stub, its manifest real.
COPY Cargo.toml Cargo.lock ./
COPY crates/ipx/Cargo.toml crates/ipx/
COPY crates/feed/Cargo.toml crates/feed/
RUN mkdir -p crates/ipx/src crates/feed/src \
    && echo 'fn main(){}' > crates/ipx/src/main.rs && touch crates/feed/src/lib.rs \
    && cargo build --release --locked \
    && rm -rf crates/ipx/src crates/feed/src

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

FROM debian:trixie-slim
# ffmpeg is DeadAir's (#171): it finds the silences and copies the frames kept. Debian's adds
# about 480 MB, once: the layer stays cached until the base image changes.
RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates gosu ffmpeg \
    && 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"]
