#!/usr/bin/env bash
set -euo pipefail

PROFILE_DIR="/www/wwwroot/storage/huawei_browser_profile"
LOG_DIR="/www/wwwroot/storage/huawei_browser_logs"
DISPLAY_ID="${HUAWEI_BROWSER_DISPLAY:-:98}"
VNC_PORT="${HUAWEI_BROWSER_VNC_PORT:-5908}"
NOVNC_PORT="${HUAWEI_BROWSER_NOVNC_PORT:-6088}"
CDP_PORT="${HUAWEI_BROWSER_CDP_PORT:-9222}"
URL="https://partner.huaweicloud.com/partnercenter/?region=cn-east-3#/obmgr/growCloud"

mkdir -p "$PROFILE_DIR" "$LOG_DIR"

pkill -f "huawei_browser_profile" 2>/dev/null || true
pkill -f "127.0.0.1:${NOVNC_PORT}" 2>/dev/null || true
pkill -f "rfbport ${VNC_PORT}" 2>/dev/null || true
pkill -f "Xvfb ${DISPLAY_ID}" 2>/dev/null || true
sleep 1

Xvfb "$DISPLAY_ID" -screen 0 1440x1000x24 -nolisten tcp >"$LOG_DIR/xvfb.log" 2>&1 &
echo $! > "$LOG_DIR/xvfb.pid"
sleep 1

DISPLAY="$DISPLAY_ID" chromium \
  --no-sandbox \
  --disable-dev-shm-usage \
  --disable-gpu \
  --password-store=basic \
  --user-data-dir="$PROFILE_DIR" \
  --remote-debugging-address=127.0.0.1 \
  --remote-debugging-port="$CDP_PORT" \
  --remote-allow-origins="*" \
  "$URL" >"$LOG_DIR/chromium.log" 2>&1 &
echo $! > "$LOG_DIR/chromium.pid"
sleep 2

x11vnc -display "$DISPLAY_ID" -localhost -nopw -forever -shared -rfbport "$VNC_PORT" >"$LOG_DIR/x11vnc.log" 2>&1 &
echo $! > "$LOG_DIR/x11vnc.pid"

websockify --web=/usr/share/novnc/ "127.0.0.1:${NOVNC_PORT}" "127.0.0.1:${VNC_PORT}" >"$LOG_DIR/novnc.log" 2>&1 &
echo $! > "$LOG_DIR/novnc.pid"

cat <<EOF
华为云服务器浏览器已启动。

本机执行 SSH 隧道:
ssh -L ${NOVNC_PORT}:127.0.0.1:${NOVNC_PORT} root@115.190.11.134

然后打开:
http://127.0.0.1:${NOVNC_PORT}/vnc.html?autoconnect=1&resize=scale

登录完成后不要退出华为云账号，直接关闭本机网页即可。
EOF
