#!/bin/sh
set -eu
mkdir -p "$HOME"
# Supply a passwd entry to GUI programs for an arbitrary host uid.
uid=$(id -u)
gid=$(id -g)
printf 'agent:x:%s:%s:Agent:%s:/bin/sh\n' "$uid" "$gid" "$HOME" > /tmp/od-passwd
printf 'agent:x:%s:\n' "$gid" > /tmp/od-group
export NSS_WRAPPER_PASSWD=/tmp/od-passwd NSS_WRAPPER_GROUP=/tmp/od-group
for lib in /usr/lib/*/libnss_wrapper.so; do
  if [ -f "$lib" ]; then export LD_PRELOAD="$lib"; break; fi
done
rm -f /tmp/od-ready
Xtigervnc :1 -geometry 1280x800 -depth 24 -SecurityTypes None -localhost yes -rfbport 5900 -AlwaysShared -nolisten tcp -ac &
vnc=$!
cleanup() {
  trap - EXIT INT TERM
  if [ -S /tmp/od-browser.sock ]; then
    printf '%s\n' '{"name":"browser_close","args":{},"owner":"shutdown","epoch":""}' | timeout 7 od-browser >/dev/null 2>&1 || true
  fi
  kill "$vnc" 2>/dev/null || true
}
trap cleanup EXIT INT TERM
attempt=0
until xdpyinfo -display :1 >/dev/null 2>&1; do
  kill -0 "$vnc"
  attempt=$((attempt+1))
  [ "$attempt" -lt 60 ] || exit 1
  sleep 1
done
openbox &
touch /tmp/od-ready
wait "$vnc"
