LazyBoy2/box/box-chrome

68 lines
2.2 KiB
Bash

#!/bin/bash
# Chromium on my computer. Same user-data-dir + CDP 9222 so Playwright can
# attach to the browser the human sees (Firefox profiles cannot).
set -euo pipefail
export DISPLAY="${DISPLAY:-:1}"
PROFILE=/home/box/chrome-profile
CDP_PORT=9222
LAUNCH_LOCK=/tmp/.box-chrome-launch.lock
# Preserve the profile from the earlier Chromium build without merging accounts.
if [[ ! -e "$PROFILE" && -d /home/box/.config/chromium ]]; then
ln -s /home/box/.config/chromium "$PROFILE"
fi
mkdir -p "$PROFILE"
cdp_up() {
python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:$CDP_PORT/json/version', timeout=1).close()" 2>/dev/null
}
profile_in_use() {
pgrep -f -- "--user-data-dir=$PROFILE" >/dev/null 2>&1
}
# The desktop autostart and the agent's ensure_browser_ready can both launch
# within the same second. Chromium's own singleton lock only exists once the
# first instance has initialised, so two cold starts race and the loser shows
# a "profile in use" dialog on the desktop. Hold a launch lock until the first
# instance is listening; later launchers then just forward their URLs to it.
exec 9>"$LAUNCH_LOCK"
flock -w 30 9 || true
if profile_in_use; then
flock -u 9
exec 9>&-
exec chromium --no-sandbox --user-data-dir="$PROFILE" "$@"
fi
# The profile lives on a volume that outlives the container. Chromium's
# SingletonLock names <hostname>-<pid>; after a container is recreated (new
# hostname) or Chromium is killed without shutdown it points at nothing, and
# Chromium refuses the profile with an "in use on another computer" dialog.
# No process in this container holds the profile (checked above), so it is
# stale by definition.
rm -f "$PROFILE/SingletonLock" "$PROFILE/SingletonSocket" "$PROFILE/SingletonCookie"
chromium \
--no-sandbox \
--disable-dev-shm-usage \
--disable-gpu \
--no-first-run --restore-last-session \
--no-default-browser-check \
--password-store=basic \
--user-data-dir="$PROFILE" \
--remote-debugging-address=127.0.0.1 \
--remote-debugging-port="$CDP_PORT" \
"$@" 9>&- &
pid=$!
trap 'kill -TERM "$pid" 2>/dev/null' TERM INT
for _ in $(seq 1 60); do
if cdp_up || ! kill -0 "$pid" 2>/dev/null; then
break
fi
sleep 0.25
done
flock -u 9
exec 9>&-
wait "$pid"