FROM vnc-server-base:latest

# 配置 nginx 反向代理 CDP
RUN cat > /etc/nginx/sites-enabled/cdp << 'EOF'
server {
    listen 9223;
    
    location / {
        proxy_pass http://127.0.0.1:9222;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
EOF

# 禁用默认站点
RUN rm -f /etc/nginx/sites-enabled/default

RUN cat > /entrypoint.sh << 'EOF'
#!/bin/bash

VNC_PWD=${VNC_PASSWORD:-"123456"}
VNC_PORT=${VNC_PORT:-5900}
DISPLAY_NUM=${DISPLAY_NUM:-99}
TARGET_URL=${TARGET_URL:-"https://www.baidu.com"}

Xvfb :${DISPLAY_NUM} -screen 0 1280x1024x24 &
sleep 2
export DISPLAY=:${DISPLAY_NUM}

CHROME_BIN=$(find /ms-playwright -name "chrome" -type f -executable 2>/dev/null | head -1)
if [ -z "$CHROME_BIN" ]; then
    CHROME_BIN=$(which chromium-browser 2>/dev/null || which google-chrome-stable 2>/dev/null || which chrome 2>/dev/null)
fi

"$CHROME_BIN" \
    --no-sandbox \
    --disable-gpu \
    --remote-debugging-port=9222 \
    --remote-debugging-address=0.0.0.0 \
    --remote-allow-origins=* \
    --disable-features=IsolateOrigins,site-per-process \
    "${TARGET_URL}" &

x11vnc -display :${DISPLAY_NUM} -forever -shared -passwd "${VNC_PWD}" -rfbport ${VNC_PORT} &

/opt/novnc/utils/novnc_proxy --vnc localhost:${VNC_PORT} --listen 6080 &

# 启动 nginx
nginx &

wait
EOF

RUN chmod +x /entrypoint.sh

EXPOSE 5900 6080 9223

ENTRYPOINT ["/entrypoint.sh"]