FROM rockylinux/rockylinux:9

ENV LANG=en_US.UTF-8 \
    LC_ALL=en_US.UTF-8 \
    DISPLAY=:99 \
    SCREEN_WIDTH=1280 \
    SCREEN_HEIGHT=720 \
    SCREEN_DEPTH=24 \
    API_PORT=8000 \
    VNC_PORT=5900 \
    NOVNC_PORT=6080 \
    VNC_VIEW_ONLY=false \
    PYTHONUNBUFFERED=1

RUN dnf install -y epel-release && \
    dnf update -y && \
    dnf install -y --allowerasing \
        python3 \
        python3-pip \
        python3-devel \
        xorg-x11-server-Xvfb \
        x11vnc \
        which \
        wget \
        git \
        procps \
        iproute \
        file \
        fontconfig \
        liberation-sans-fonts \
        dejavu-sans-fonts \
        google-noto-sans-cjk-ttc-fonts \
        google-noto-emoji-color-fonts \
        nss \
        atk \
        cups-libs \
        libXcomposite \
        libXdamage \
        libXrandr \
        mesa-libgbm \
        pango \
        libdrm \
        libxkbcommon \
        alsa-lib \
        at-spi2-atk \
        libXScrnSaver \
    && dnf clean all && \
    rm -rf /var/cache/dnf

RUN dnf install -y openbox 2>/dev/null || \
    echo "WARNING: openbox not found, will run without window manager"

COPY requirements.txt /tmp/requirements.txt
RUN pip3 install --no-cache-dir --upgrade pip && \
    pip3 install --no-cache-dir -r /tmp/requirements.txt

RUN playwright install chromium

RUN git clone --depth 1 --branch v1.2.0 https://github.com/novnc/noVNC.git /opt/novnc && \
    rm -rf /opt/novnc/.git && \
    sed -i 's|</head>|<script>if(!location.search.includes("view_only")){var u=new URL(location.href);u.searchParams.set("view_only","1");u.searchParams.set("autoconnect","1");history.replaceState(null,"",u)}</script></head>|' /opt/novnc/vnc.html

WORKDIR /app
COPY . /app

RUN sed -i 's/\r$//' /app/scripts/entrypoint.sh /app/scripts/start_wm.sh /app/scripts/start_x11vnc.sh && \
    chmod +x /app/scripts/entrypoint.sh /app/scripts/start_wm.sh /app/scripts/start_x11vnc.sh

EXPOSE ${API_PORT} ${VNC_PORT} ${NOVNC_PORT}

VOLUME ["/app/data"]

HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
    CMD curl -f http://localhost:${API_PORT}/health || exit 1

CMD ["/app/scripts/entrypoint.sh"]
