# Wild Dragon Playout sidecar — CasparCG Server + Node AMCP control shim.
#
# CasparCG's mixer needs an OpenGL context. On a node with a real GPU we'd pass
# the device + driver through; for the headless / no-GPU case we run a virtual
# framebuffer (Xvfb) so the GL context initialises. The container is launched
# --privileged by mam-api (same as capture) so DeckLink / NDI hardware is
# reachable when present.
#
# NDI + DeckLink SDKs are NOT redistributable. They are fetched at build time
# from URLs supplied as build args (mirror them into your own artifact store);
# the build still succeeds without them (NDI/DeckLink consumers simply won't be
# available — SRT/RTMP/test output still work).

FROM node:20-bookworm

ARG CASPAR_VERSION=2.3.3-stable
ARG CASPAR_URL=https://github.com/CasparCG/server/releases/download/v2.3.3-stable/CasparCG-Server-2.3.3-stable-Linux.tar.gz
ARG NDI_SDK_URL=

ENV DEBIAN_FRONTEND=noninteractive

# CasparCG 2.3 Linux runtime deps + Xvfb for headless GL + ffmpeg libs for the
# FFMPEG consumer (SRT/RTMP output).
RUN apt-get update && apt-get install -y --no-install-recommends \
      ca-certificates curl tar xz-utils \
      xvfb libgl1-mesa-glx libgl1-mesa-dri libglu1-mesa \
      libx11-6 libxext6 libxrandr2 libxcursor1 libxinerama1 libxi6 \
      libopenal1 libsndfile1 libavformat59 libavcodec59 libavfilter8 \
      libswscale6 libswresample4 libpostproc56 fonts-dejavu-core \
  && rm -rf /var/lib/apt/lists/*

# ── CasparCG Server ──────────────────────────────────────────────────────────
WORKDIR /opt
RUN curl -fsSL "$CASPAR_URL" -o caspar.tar.gz \
  && mkdir -p /opt/casparcg \
  && tar xzf caspar.tar.gz -C /opt/casparcg --strip-components=1 \
  && rm caspar.tar.gz \
  && (test -f /opt/casparcg/casparcg || test -f /opt/casparcg/CasparCG\ Server || true)

# ── NDI runtime (optional) ───────────────────────────────────────────────────
# If an NDI SDK tarball URL is provided, extract its libs to /opt/ndi-lib and
# point CasparCG at them via NDI_RUNTIME_DIR_V6. Pin the SDK version to what the
# server expects (the common docker failure is a libndi .so version mismatch).
RUN if [ -n "$NDI_SDK_URL" ]; then \
      mkdir -p /opt/ndi-lib && \
      curl -fsSL "$NDI_SDK_URL" -o /tmp/ndi.tar.gz && \
      tar xzf /tmp/ndi.tar.gz -C /tmp && \
      find /tmp -name 'libndi*.so*' -exec cp -a {} /opt/ndi-lib/ \; && \
      rm -f /tmp/ndi.tar.gz && ldconfig /opt/ndi-lib || true; \
    fi
ENV NDI_RUNTIME_DIR_V6=/opt/ndi-lib

# CasparCG media folder — mam-api stages assets from S3 into this volume.
RUN mkdir -p /media

# ── Node control shim ────────────────────────────────────────────────────────
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
COPY . .

# CasparCG config + entrypoint
COPY casparcg.config /opt/casparcg/casparcg.config
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

EXPOSE 3002 5250
ENTRYPOINT ["/entrypoint.sh"]
