FROM mcr.microsoft.com/playwright:v1.48.0-jammy

ENV DEBIAN_FRONTEND=noninteractive

# ========== 安装 VNC 相关软件 ==========
RUN apt-get update && \
    apt-get install -y \
        x11vnc \
        xvfb \
        fluxbox \
        git \
        tigervnc-standalone-server \
        wget \
        curl \
    && rm -rf /var/lib/apt/lists/*

# ========== 安装 noVNC ==========
RUN git clone https://github.com/novnc/noVNC.git /opt/novnc && \
    git clone https://github.com/novnc/websockify.git /opt/novnc/utils/websockify

# ========== 创建启动脚本 ==========
RUN cat > /entrypoint.sh << 'EOF'
#!/bin/bash

# 设置 VNC 密码（从环境变量读取）
if [ ! -z "$VNC_PASSWORD" ]; then
    mkdir -p /root/.vnc
    echo "$VNC_PASSWORD" | vncpasswd -f > /root/.vnc/passwd
    chmod 600 /root/.vnc/passwd
    VNC_SECURITY="-SecurityTypes VncAuth -PasswordFile /root/.vnc/passwd"
else
    VNC_SECURITY="-SecurityTypes None"
fi

# 启动虚拟显示
Xvfb :1 -screen 0 1280x1024x24 &
export DISPLAY=:1

# 等待 Xvfb 启动
sleep 2

# 启动窗口管理器
fluxbox &

# 启动 VNC 服务器（使用 tigervnc）
vncserver :1 -geometry 1280x1024 -depth 24 \
    -localhost no \
    -verbose \
    $VNC_SECURITY || true

# 启动 noVNC Web 代理
/opt/novnc/utils/novnc_proxy --vnc localhost:5901 --listen 6080 &

# 等待服务启动
sleep 5

# 获取 Playwright 安装的 Chromium 路径
CHROMIUM_PATH=$(find /ms-playwright -name "chrome" -type f -executable | head -1)
if [ -z "$CHROMIUM_PATH" ]; then
    echo "Warning: Chromium not found, using system chrome"
    CHROMIUM_PATH="google-chrome"
fi

echo "Using Chromium: $CHROMIUM_PATH"

# 启动 Chromium
$CHROMIUM_PATH \
    --no-sandbox \
    --disable-gpu \
    --remote-debugging-port=9222 \
    --remote-debugging-address=0.0.0.0 \
    --window-size=1280,1024 \
    --disable-dev-shm-usage \
    --disable-setuid-sandbox \
    --user-data-dir=/tmp/chromium-profile &

# 保持容器运行
wait
EOF

RUN chmod +x /entrypoint.sh

# ========== 暴露端口 ==========
EXPOSE 6080 9222

# ========== 设置入口点 ==========
ENTRYPOINT ["/entrypoint.sh"]