FROM node:22-slim AS base

ARG CAMOUFOX_VERSION=135.0.1
ARG CAMOUFOX_RELEASE=beta.24
ARG ARCH=x86_64

RUN apt-get update && apt-get install -y \
    libgtk-3-0 libdbus-glib-1-2 libxt6 libasound2 libx11-xcb1 libxcomposite1 \
    libxcursor1 libxdamage1 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 \
    libxtst6 libegl1-mesa libgl1-mesa-dri libgbm1 xvfb x11vnc \
    fonts-liberation fonts-noto-color-emoji fontconfig ca-certificates curl unzip \
    python3-minimal python3-pip python3-venv \
    && rm -rf /var/lib/apt/lists/*

# noVNC web client
RUN mkdir -p /usr/share/novnc && \
    curl -fsSL https://github.com/novnc/noVNC/archive/refs/tags/v1.5.0.tar.gz | \
    tar xz -C /usr/share/novnc --strip-components=1 && \
    curl -fsSL https://github.com/novnc/websockify/archive/refs/tags/v0.12.0.tar.gz | \
    tar xz -C /usr/share/novnc/utils --strip-components=1

# websockify CLI (pip install required — the bundled version needs it as a module)
RUN pip3 install --break-system-packages websockify

RUN --mount=type=bind,source=dist,target=/dist \
    mkdir -p /root/.cache/camoufox && \
    (unzip -q /dist/camoufox-${ARCH}.zip -d /root/.cache/camoufox || true) && \
    chmod -R 755 /root/.cache/camoufox && \
    echo "{\"version\":\"${CAMOUFOX_VERSION}\",\"release\":\"${CAMOUFOX_RELEASE}\"}" > /root/.cache/camoufox/version.json && \
    test -f /root/.cache/camoufox/camoufox-bin

RUN --mount=type=bind,source=dist,target=/dist \
    install -m 755 /dist/yt-dlp-${ARCH} /usr/local/bin/yt-dlp

WORKDIR /app
COPY package.json ./
COPY scripts/ ./scripts/
RUN npm install --production
COPY server.js ./
COPY camofox.config.json ./
COPY lib/ ./lib/
COPY plugins/ ./plugins/
COPY scripts/ ./scripts/

RUN sh scripts/install-plugin-deps.sh

ENV NODE_ENV=production
ENV CAMOFOX_PORT=9377
EXPOSE 9377
CMD ["sh", "-c", "node --max-old-space-size=${MAX_OLD_SPACE_SIZE:-128} server.js"]
