# Kinode Media Server, container image.
#
# Built from the Linux release tarball, so the image runs exactly the bundled
# Node and BtbN ffmpeg the tarball and the .deb run. packaging/linux/build.sh
# puts this file, the compose file and the tarballs in one folder:
#   docker build -t kinode-media-server:1.5.0 .
#   docker buildx build --platform linux/amd64,linux/arm64 -t kinode-media-server:1.5.0 .
#
# Graphics card: NVIDIA through the NVIDIA Container Toolkit (gpus: all in
# compose; NVENC/NVDEC need the "video" capability, set below). Intel/AMD
# through VA-API or Quick Sync: pass /dev/dri in (devices: in compose).
FROM debian:bookworm-slim

ARG KINODE_VERSION=1.5.0
ARG TARGETARCH=amd64
ARG KINODE_UID=10001
ARG KINODE_GID=10001

# fonts for burned-in subtitles, certificates for the metadata services,
# tini to pass signals, python3-venv for Kometa (Settings, Collections)
RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates fontconfig fonts-dejavu-core tini python3 python3-venv \
 && rm -rf /var/lib/apt/lists/* \
 && groupadd --system --gid "$KINODE_GID" kinode \
 && useradd --system --uid "$KINODE_UID" --gid kinode --home-dir /data --no-create-home --shell /usr/sbin/nologin kinode \
 && install -d -o kinode -g kinode -m 0750 /data

# ADD unpacks each local .tar.gz it matches (x64, and arm64 when built)
ADD kinode-media-server-${KINODE_VERSION}-linux-*.tar.gz /tmp/rel/
RUN set -e; a=x64; [ "$TARGETARCH" = arm64 ] && a=arm64; \
    [ -d "/tmp/rel/kinode-media-server-${KINODE_VERSION}-linux-$a" ] || { echo "no $a release tarball in the build folder" >&2; exit 1; }; \
    mv "/tmp/rel/kinode-media-server-${KINODE_VERSION}-linux-$a" /opt/kinode-media-server; \
    rm -rf /tmp/rel; \
    echo docker > /opt/kinode-media-server/app/install-type; \
    /opt/kinode-media-server/node/bin/node -e 'process.exit(0)'; \
    /opt/kinode-media-server/app/vendor/ffmpeg/bin/ffmpeg -hide_banner -version | head -n 1
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh

ENV PORT=5466 \
    KINODE_DATA=/data \
    KINODE_SUPERVISED=docker \
    NODE_ENV=production \
    PATH=/opt/kinode-media-server/node/bin:$PATH \
    NVIDIA_VISIBLE_DEVICES=all \
    NVIDIA_DRIVER_CAPABILITIES=compute,video,utility

WORKDIR /opt/kinode-media-server/app
USER kinode
VOLUME ["/data"]
EXPOSE 5466/tcp 5467/udp

HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||5466)+'/').then(r=>process.exit(r.status<500?0:1),()=>process.exit(1))"

ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/docker-entrypoint.sh"]
CMD ["node", "/opt/kinode-media-server/app/server.js"]
