#!/bin/bash
set -uo pipefail

desktop=${BASH_SOURCE[0]%/*}/desktop
if command -v hsetroot >/dev/null && [ -r "$desktop/openbot-logo.png" ]; then
  hsetroot -solid '#1a1a1a' -center "$desktop/openbot-logo.png" >/dev/null 2>&1 || true
fi
if ! command -v openbox >/dev/null; then
  echo "openbox is not installed. The agent display has no window manager." >&2
  exit 0
fi
export XDG_CONFIG_DIRS="$desktop:${XDG_CONFIG_DIRS:-/etc/xdg}"
export XDG_DATA_DIRS="$desktop:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"

cd "$HOME" || true

failures=0
while [ "$failures" -lt 5 ] && xdpyinfo >/dev/null 2>&1; do
  started=$SECONDS
  (
    echo 500 >/proc/self/oom_score_adj 2>/dev/null
    exec nice -n 10 openbox --config-file "$desktop/openbox/openbot-rc.xml" >/dev/null 2>&1
  )
  if [ $((SECONDS - started)) -lt 10 ]; then failures=$((failures + 1)); else failures=0; fi
  sleep 2
done
[ "$failures" -lt 5 ] || echo "openbox stopped 5 times at start. The agent display has no window manager." >&2
