#!/usr/bin/env bash
# Wait for the desktop, then launch Chrome on :1 so the VNC screen shows a
# controllable browser (jarvis can also drive it). Runs as root -> --no-sandbox.
set -e
for i in $(seq 1 40); do
  xdpyinfo -display :1 >/dev/null 2>&1 && break
  sleep 1
done
sleep 3
export DISPLAY=:1

# Suppress the "--no-sandbox unsupported flag" warning bar via a managed policy
# instead of --test-type. --test-type is an automation signal Google can flag,
# so we keep the launch flags minimal/clean (less chance of the /sorry/ bot
# challenge) while still hiding the infobar.
mkdir -p /etc/opt/chrome/policies/managed
cat > /etc/opt/chrome/policies/managed/jarvis.json <<'JSON'
{ "CommandLineFlagSecurityWarningsEnabled": false }
JSON

# Seed the profile's web-content language to Korean so sites (YouTube, Google,
# Naver) render in Korean. --lang sets Chrome's own UI, but the Accept-Language
# sent to sites comes from the profile's intl.accept_languages, which a persisted
# user-data-dir would otherwise keep at en-US regardless of --accept-lang.
PREFS_DIR="${CHROME_PROFILE_DIR:-/root/chrome-profile}/Default"
PREFS="${PREFS_DIR}/Preferences"
mkdir -p "$PREFS_DIR"
if [ -f "$PREFS" ]; then
  python3 - "$PREFS" <<'PY' 2>/dev/null || true
import json, sys
p = sys.argv[1]
d = json.load(open(p))
d.setdefault("intl", {})
d["intl"]["accept_languages"] = "ko-KR,ko"
d["intl"]["selected_languages"] = "ko-KR,ko"
json.dump(d, open(p, "w"), ensure_ascii=False)
PY
else
  printf '%s' '{"intl":{"accept_languages":"ko-KR,ko","selected_languages":"ko-KR,ko"}}' > "$PREFS"
fi

# Minimal, non-automation flags. --remote-debugging exposes CDP so the brain can
# drive this on-screen Chrome (Google/YouTube/Naver), --disable-features=Translate
# hides the translate popup. NO --test-type / --disable-blink-features.
exec google-chrome \
  --no-sandbox --no-first-run --disable-dev-shm-usage \
  --no-default-browser-check \
  --disable-features=Translate,TranslateUI \
  --lang=ko-KR \
  --accept-lang=ko-KR,ko \
  --remote-debugging-port="${CDP_PORT:-9222}" \
  --remote-debugging-address="${CDP_BIND:-127.0.0.1}" \
  --user-data-dir="${CHROME_PROFILE_DIR:-/root/chrome-profile}" \
  --password-store=basic --start-maximized \
  "${CHROME_START_URL:-about:blank}"
