FROM node:24-bookworm

RUN apt-get update \
    && apt-get install -y \
    ca-certificates curl wget unzip \
    python3 tini \
    && rm -rf /var/lib/apt/lists/*

ENV NODE_ENV=production

RUN corepack enable

# Download llama.cpp binary
WORKDIR /opt/llama
RUN wget -q https://github.com/ggml-org/llama.cpp/releases/download/b5449/llama-b5449-bin-ubuntu-x64.zip \
    && unzip llama-b5449-bin-ubuntu-x64.zip \
    && rm llama-b5449-bin-ubuntu-x64.zip \
    && chmod +x /opt/llama/build/bin/llama-mtmd-cli

# Create non-root user for security
RUN groupadd -r transcribe && useradd -r -g transcribe -m transcribe

WORKDIR /app

COPY .yarn/releases ./.yarn/releases
COPY .yarn/patches ./.yarn/patches
COPY package.json .
COPY .yarnrc.yml .
COPY yarn.lock .
COPY gulpfile.js .
COPY tsconfig.json .
COPY packages/lib ./packages/lib
COPY packages/utils ./packages/utils
COPY packages/tools ./packages/tools
COPY packages/renderer ./packages/renderer
COPY packages/htmlpack ./packages/htmlpack
COPY packages/transcribe ./packages/transcribe

# We don't want to build onenote-converter since it is not used by the server
RUN sed --in-place '/onenote-converter/d' ./packages/lib/package.json

RUN BUILD_SEQUENCIAL=1 yarn install --inline-builds \
    && yarn cache clean \
    && rm -rf .yarn/berry

# Create data directory and set permissions
RUN mkdir -p /data/images \
    && chown -R transcribe:transcribe /data

WORKDIR /app/packages/transcribe

# Switch to non-root user
USER transcribe

# Set environment variables
ENV HTR_CLI_BINARY_PATH=/opt/llama/build/bin/llama-mtmd-cli
ENV LD_LIBRARY_PATH=/opt/llama/build/bin
ENV DATA_DIR=/data
ENV QUEUE_DRIVER=sqlite

# Start the Node.js application
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["yarn", "start"]
