FROM node:24 AS nodebuild

WORKDIR /build

COPY package.json package-lock.json ./
RUN npm ci

COPY webpack.config.js ./
COPY src ./src
COPY privatestudio ./privatestudio
RUN mkdir -p privatestudio/static/bundle && npm run build


FROM debian:trixie-slim AS bento4

# Bento4 tools for HLS packaging (mp4fragment, mp4hls).
ARG BENTO4_VERSION=1-6-0-641
ARG BENTO4_SHA256=d48dc6b164941212e5614237b4d9aeff81d4d111ee8b1508892764078a0870e8

RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl unzip \
    && rm -rf /var/lib/apt/lists/*
RUN curl -fsSLo /tmp/bento4.zip "https://www.bok.net/Bento4/binaries/Bento4-SDK-${BENTO4_VERSION}.x86_64-unknown-linux.zip" \
    && echo "${BENTO4_SHA256}  /tmp/bento4.zip" | sha256sum -c - \
    && unzip -q /tmp/bento4.zip -d /tmp \
    && mkdir -p /opt/bento4 \
    && cp -r "/tmp/Bento4-SDK-${BENTO4_VERSION}.x86_64-unknown-linux/bin" "/tmp/Bento4-SDK-${BENTO4_VERSION}.x86_64-unknown-linux/utils" /opt/bento4/


FROM python:3.13-slim-trixie

# Version used by setuptools_scm, since .git is not copied into the image.
ARG VERSION=0.0.0

RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg \
    && rm -rf /var/lib/apt/lists/*

COPY --from=bento4 /opt/bento4 /opt/bento4
ENV PATH="/opt/bento4/bin:${PATH}"

RUN useradd --create-home privatestudio

EXPOSE 8000

ENV PYTHONUNBUFFERED=1 \
    PORT=8000 \
    DJANGO_SETTINGS_MODULE=privatestudio.settings.production \
    STORAGE_PATH=/data/storage

RUN pip install --no-cache-dir "gunicorn~=23.0" "psycopg2-binary~=2.9.11"

WORKDIR /app

COPY --chown=privatestudio:privatestudio . .
COPY --from=nodebuild --chown=privatestudio:privatestudio /build/privatestudio/static/bundle ./privatestudio/static/bundle

RUN SETUPTOOLS_SCM_PRETEND_VERSION="${VERSION}" pip install --no-cache-dir . \
    && mkdir -p /data/storage && chown -R privatestudio:privatestudio /data /app

USER privatestudio

RUN python manage.py collectstatic --noinput --clear

VOLUME ["/data"]

# Run the job worker from the same image with the same /data volume:
#   docker run -v privatestudio-data:/data <image> python manage.py run_worker
# Migrating at startup keeps "docker run" simple. Use a release step instead if
# you run more than one container against the same database.
CMD set -xe; \
    python manage.py migrate --noinput; \
    exec gunicorn privatestudio.wsgi:application \
        --bind 0.0.0.0:${PORT} \
        -k gthread --workers 2 --threads 8 --timeout 600
