FROM debian:trixie-slim AS base
ENV DEBIAN_FRONTEND=noninteractive

# Install sys utils, dependencies and nginx
RUN apt-get update && \
    apt-get install -yq nginx npm python3 python3-pip 

# Copy files
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

RUN mkdir /simple-chat
COPY . /simple-chat

# Install app dependencies
RUN pip3 install -r /simple-chat/simple_chat_api/requirements.txt --break-system-packages --ignore-installed
RUN npm install --prefix /simple-chat/frontend || true

# Building
# || true to allow failure
RUN npm run build --prefix /simple-chat/frontend || true

# Setup nginx
RUN rm /etc/nginx/nginx.conf
RUN ln -s /simple-chat/docker/nginx.conf /etc/nginx/nginx.conf
RUN mkdir -p /var/nginx

# Dev stage
FROM base AS dev
ARG ROOT_PASSWD
ENV PIP_BREAK_SYSTEM_PACKAGES=1
ENV DEV=true

# additional dependencies for dev
RUN apt-get update && \
    apt-get install -y build-essential git openssh-server

# SSH configuration
RUN if [ -n "$ROOT_PASSWD" ]; then echo "root:$ROOT_PASSWD" | chpasswd; else passwd -d root; fi && \
    echo "PermitRootLogin yes" > /etc/ssh/sshd_config && \
    echo "ListenAddress 0.0.0.0" >> /etc/ssh/sshd_config && \
    echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config && \
    echo "PermitEmptyPasswords no" >> /etc/ssh/sshd_config && \
    echo "Subsystem sftp /usr/lib/ssh/sftp-server" >> /etc/ssh/sshd_config

RUN ssh-keygen -A && \
    # echo "sshd: ALL" > /etc/hosts.deny && \
    echo "sshd: ALL" > /etc/hosts.allow

# Run entrypoint for dev
CMD ["bash", "/entrypoint.sh"]

# Production stage
FROM base AS prod
# Run entrypoint
CMD ["bash", "/entrypoint.sh"]
