FROM kasmweb/chrome:1.19.0

USER root

# Install Node.js 20.x
RUN rm -f /etc/apt/sources.list.d/google-chrome.list && \
    apt-get update && \
    apt-get install -y curl && \
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
    apt-get install -y nodejs && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Create app directory and set ownership to kasm-user
RUN mkdir -p /app && chown -R 1000:1000 /app

# Switch to kasm-user to run npm install safely
USER 1000
WORKDIR /app

# Copy application files (ignoring node_modules and browser_profiles)
COPY --chown=1000:1000 . /app

# Pre-create the browser_profiles and data directory so the volume inherits the correct ownership
RUN mkdir -p /app/browser_profiles /app/data && chown -R 1000:1000 /app/browser_profiles /app/data

# Install Node dependencies
RUN npm install

# Create a custom entrypoint script
USER root
RUN echo '#!/bin/bash\n\
# Start Kasm VNC server in the background\n\
/dockerstartup/vnc_startup.sh &\n\
\n\
# Wait for the X server to fully initialize\n\
sleep 5\n\
\n\
# Set environment variables for YOUChat_Proxy\n\
export USE_MANUAL_LOGIN="true"\n\
export HIDE_BROWSER="false"\n\
export BROWSER_PATH="/usr/bin/google-chrome"\n\
export DISPLAY=:1\n\
\n\
# Start the proxy server\n\
cd /app\n\
node src/index.mjs\n\
' > /app/start-proxy.sh && chmod +x /app/start-proxy.sh

USER 1000

# Expose Kasm VNC port and Proxy API port
EXPOSE 6901 8080

ENTRYPOINT ["/app/start-proxy.sh"]