FROM node:24.5.0-slim AS builder

RUN apt-get update && apt-get install -y python3 python3-pip sqlite3 && rm -rf /var/lib/apt/lists/*

WORKDIR /home/gooseek

COPY package.json package-lock.json ./
COPY apps/frontend/package.json ./apps/frontend/
COPY apps/shared-types/package.json ./apps/shared-types/
COPY apps/shared-utils/package.json ./apps/shared-utils/

RUN npm install

COPY apps ./apps

RUN mkdir -p /home/gooseek/apps/frontend/data
ENV DATA_DIR=/home/gooseek/apps/frontend
RUN npm run build

FROM node:24.5.0-slim

RUN apt-get update && apt-get install -y \
    python3-dev python3-babel python3-venv python-is-python3 \
    uwsgi uwsgi-plugin-python3 \
    git build-essential libxslt-dev zlib1g-dev libffi-dev libssl-dev \
    curl sudo \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /home/gooseek

COPY --from=builder /home/gooseek/apps/frontend/public ./public
COPY --from=builder /home/gooseek/apps/frontend/.next/static ./public/_next/static
COPY --from=builder /home/gooseek/apps/frontend/.next/standalone ./
COPY --from=builder /home/gooseek/apps/frontend/drizzle ./drizzle

RUN mkdir -p /home/gooseek/data /home/gooseek/uploads

RUN useradd --shell /bin/bash --system \
    --home-dir "/usr/local/searxng" \
    --comment 'Privacy-respecting metasearch engine' \
    searxng

RUN mkdir "/usr/local/searxng"
RUN mkdir -p /etc/searxng
RUN chown -R "searxng:searxng" "/usr/local/searxng"

COPY docker/searxng/settings.yml /etc/searxng/settings.yml
COPY docker/searxng/limiter.toml /etc/searxng/limiter.toml
COPY docker/searxng/uwsgi.ini /etc/searxng/uwsgi.ini
RUN chown -R searxng:searxng /etc/searxng

USER searxng

RUN git clone "https://github.com/searxng/searxng" \
                   "/usr/local/searxng/searxng-src"

RUN python3 -m venv "/usr/local/searxng/searx-pyenv"
RUN "/usr/local/searxng/searx-pyenv/bin/pip" install --upgrade pip setuptools wheel pyyaml msgspec
RUN cd "/usr/local/searxng/searxng-src" && \
    "/usr/local/searxng/searx-pyenv/bin/pip" install --use-pep517 --no-build-isolation -e .

USER root

WORKDIR /home/gooseek
COPY docker/entrypoint.sh ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
RUN sed -i 's/\r$//' ./entrypoint.sh || true

RUN echo "searxng ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

EXPOSE 3000 8080

ENV SEARXNG_API_URL=http://localhost:8080
ENV DATA_DIR=/home/gooseek

CMD ["/home/gooseek/entrypoint.sh"]
