FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

# Update with future time fix and install build dependencies
RUN apt-get -o Acquire::Max-FutureTime=86400 update -y --fix-missing
RUN apt-get install -y build-essential xorg libx11-dev libxext-dev libbsd-dev libpthread-stubs0-dev libasound2-dev libxrandr-dev libxi-dev libgl1-mesa-dev libglu1-mesa-dev libxcursor-dev libxinerama-dev libwayland-dev libxkbcommon-dev

# Build the miniRT project
WORKDIR /best_rt
COPY . .
RUN make

# Install VNC and graphics dependencies
RUN apt-get update && apt-get install -y \
    tigervnc-standalone-server \
    python3 \
    python3-pip \
    wget \
    git \
    openbox \
    x11-utils \
    libgl1-mesa-dev \
    libglu1-mesa-dev \
    net-tools \
    procps \
    lsof \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install websockify
RUN pip3 install websockify --break-system-packages

# Install noVNC
RUN git clone https://github.com/novnc/noVNC.git /opt/noVNC

# Create VNC directory and set password
RUN mkdir -p /root/.vnc && \
    echo "password" | vncpasswd -f > /root/.vnc/passwd && \
    chmod 600 /root/.vnc/passwd

RUN rm /opt/noVNC/*.html
RUN mv /best_rt/vnc/minimal.html /opt/noVNC/vnc.html

RUN echo '<!DOCTYPE html>\n\
<html>\n\
<head>\n\
    <title>miniRT</title>\n\
    <style>\n\
        body { margin: 0; padding: 0; background: #000; overflow: hidden; }\n\
        iframe { width: 100vw; height: 100vh; border: none; }\n\
    </style>\n\
</head>\n\
<body>\n\
    <iframe src="/clean.html"></iframe>\n\
</body>\n\
</html>' > /opt/noVNC/minimal.html

# Create VNC startup script that keeps session alive
RUN echo '#!/bin/bash\n\
export USER=root\n\
export HOME=/root\n\
xsetroot -solid grey\n\
# Start openbox to keep session alive\n\
openbox-session &\n\
# Keep the session running\n\
while true; do sleep 3600; done\n\
' > /root/.vnc/xstartup && chmod +x /root/.vnc/xstartup

# Create connection monitor script
RUN echo '#!/bin/bash\n\
\n\
APP_PID=""\n\
CLIENT_TIMEOUT=30  # Stop app after 30 seconds of no clients\n\
CHECK_INTERVAL=5   # Check every 5 seconds\n\
\n\
log() {\n\
    echo "[$(date "+%H:%M:%S")] $1"\n\
}\n\
\n\
has_vnc_clients() {\n\
    # Check for active VNC connections\n\
    netstat -tn 2>/dev/null | grep -q ":5901.*ESTABLISHED"\n\
}\n\
\n\
has_websocket_clients() {\n\
    # Check for active WebSocket connections (noVNC)\n\
    netstat -tn 2>/dev/null | grep -q ":6080.*ESTABLISHED"\n\
}\n\
\n\
start_app() {\n\
    if [ -z "$APP_PID" ] || ! kill -0 "$APP_PID" 2>/dev/null; then\n\
        log "Starting miniRT application..."\n\
        cd /best_rt\n\
        /best_rt/miniRT /best_rt/scenes/multilight.rt &\n\
        APP_PID=$!\n\
        log "miniRT started with PID: $APP_PID"\n\
    fi\n\
}\n\
\n\
stop_app() {\n\
    if [ -n "$APP_PID" ] && kill -0 "$APP_PID" 2>/dev/null; then\n\
        log "Stopping miniRT application (PID: $APP_PID)..."\n\
        kill "$APP_PID" 2>/dev/null\n\
        wait "$APP_PID" 2>/dev/null\n\
        APP_PID=""\n\
        log "miniRT stopped"\n\
    fi\n\
}\n\
\n\
# Main monitoring loop\n\
last_client_time=0\n\
\n\
while true; do\n\
    current_time=$(date +%s)\n\
    \n\
    if has_vnc_clients || has_websocket_clients; then\n\
        # Client connected\n\
        last_client_time=$current_time\n\
        start_app\n\
    else\n\
        # No clients\n\
        if [ "$last_client_time" -gt 0 ]; then\n\
            time_since_last_client=$((current_time - last_client_time))\n\
            if [ "$time_since_last_client" -gt "$CLIENT_TIMEOUT" ]; then\n\
                stop_app\n\
                last_client_time=0\n\
            fi\n\
        fi\n\
    fi\n\
    \n\
    sleep "$CHECK_INTERVAL"\n\
done\n\
' > /monitor-clients.sh && chmod +x /monitor-clients.sh

# Create a simple mime.types file for websockify
RUN echo 'text/html                             html htm shtml;\n\
application/javascript                  js;\n\
text/css                               css;\n\
image/png                              png;\n\
image/jpeg                             jpg jpeg;\n\
image/gif                              gif;\n\
image/svg+xml                          svg;\n\
' > /opt/noVNC/mime.types

# Create smart startup script
RUN echo '#!/bin/bash\n\
export USER=root\n\
export HOME=/root\n\
export DISPLAY=:1\n\
\n\
log() {\n\
    echo "[$(date "+%H:%M:%S")] $1"\n\
}\n\
\n\
log "Starting VNC server..."\n\
vncserver :1 -geometry 1920x1080 -depth 24 -localhost no\n\
sleep 5\n\
\n\
log "Starting noVNC web interface..."\n\
cd /opt/noVNC\n\
python3 -m websockify 6080 localhost:5901 &\n\
NOVNC_PID=$!\n\
\n\
sleep 3\n\
xhost + 2>/dev/null || true\n\
\n\
log "VNC ready at http://localhost:6080/vnc.html"\n\
log "Starting client monitor..."\n\
log "miniRT will start automatically when a client connects"\n\
log "miniRT will stop automatically when no clients for 30 seconds"\n\
\n\
# Start the client monitor\n\
/monitor-clients.sh &\n\
MONITOR_PID=$!\n\
\n\
# Handle cleanup on exit\n\
cleanup() {\n\
    log "Shutting down..."\n\
    kill $NOVNC_PID 2>/dev/null\n\
    kill $MONITOR_PID 2>/dev/null\n\
    vncserver -kill :1 2>/dev/null\n\
    exit 0\n\
}\n\
\n\
trap cleanup SIGTERM SIGINT\n\
\n\
# Wait for processes\n\
wait\n\
' > /start.sh && chmod +x /start.sh

EXPOSE 6080 5901

CMD ["/start.sh"]
