#!/bin/sh
# ANODE X11 desktop session entrypoint (strict POSIX sh)
set -u

: "${XDG_CONFIG_HOME:=$HOME/.config}"
: "${ANODE_PREFIX:=/usr/local}"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"

# Ensure ANODE prefix binaries are on PATH
case ":$PATH:" in
  *":$SCRIPT_DIR:"*) ;;
  *) PATH="$SCRIPT_DIR:$PATH" ;;
esac
case ":$PATH:" in
  *":$ANODE_PREFIX/bin:"*) ;;
  *) PATH="$ANODE_PREFIX/bin:$PATH" ;;
esac
export PATH

for _envfile in "$ANODE_PREFIX/share/anode/env.sh" "$SCRIPT_DIR/../data/env.sh"; do
  if [ -r "$_envfile" ]; then
    . "$_envfile"
    break
  fi
done
unset _envfile

if [ ! -f "$XDG_CONFIG_HOME/anode/scale.conf" ] && command -v anode-apply-scale >/dev/null 2>&1; then
  anode-apply-scale auto --no-apply >/dev/null 2>&1 || true
fi
if [ -f "$XDG_CONFIG_HOME/anode/scale.env" ]; then
  . "$XDG_CONFIG_HOME/anode/scale.env"
fi

if [ ! -f "$HOME/.Xresources" ] && command -v anode-apply-theme >/dev/null 2>&1; then
  anode-apply-theme AnodeDefault >/dev/null 2>&1 || true
elif [ -f "$HOME/.Xresources" ] && command -v xrdb >/dev/null 2>&1; then
  xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true
fi

if command -v xsetroot >/dev/null 2>&1; then
  xsetroot -cursor_name left_ptr >/dev/null 2>&1 || true
fi

BG_PIDS=""
spawn_bg() {
  if command -v "$1" >/dev/null 2>&1; then
    "$@" >/dev/null 2>&1 &
    BG_PIDS="$BG_PIDS $!"
  fi
}

cleanup_bg() {
  for _pid in $BG_PIDS; do
    kill "$_pid" 2>/dev/null || true
  done
}
trap cleanup_bg EXIT INT TERM

spawn_bg xsettingsd
spawn_bg dunst
spawn_bg anode-statusd
spawn_bg anode-powerd
spawn_bg anode-touchd

if [ "${ANODE_TOUCH:-0}" = "1" ]; then
  spawn_bg anode-vkbd
fi

if command -v dwm >/dev/null 2>&1; then
  dwm
else
  printf 'anode-session: dwm executable not found\n' >&2
  exit 1
fi
