#!/bin/sh

LOG="${HOME}/.xsession-errors"
_uid="$(id -u)"
export XDG_RUNTIME_DIR="/var/run/user/${_uid}"
mkdir -p "/tmp/clawdie/cache" "${HOME}/.config/clawdie" "${XDG_RUNTIME_DIR}" 2>/dev/null || true
chown "$(id -un):$(id -gn)" /tmp/clawdie /tmp/clawdie/cache "${XDG_RUNTIME_DIR}" 2>/dev/null || true
chmod 0700 /tmp/clawdie /tmp/clawdie/cache "${XDG_RUNTIME_DIR}" 2>/dev/null || true
mkdir -p "${HOME}/.cache/sessions"
touch "$LOG"
chmod 0644 "$LOG" 2>/dev/null || true
exec >>"$LOG" 2>&1

echo "=== $(date -u '+%Y-%m-%dT%H:%M:%SZ') clawdie-xfce-session start ==="

export PATH="/opt/clawdie/npm-global/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH}"
export XDG_CURRENT_DESKTOP="XFCE"
export XDG_MENU_PREFIX="xfce-"
export DESKTOP_SESSION="clawdie-xfce"
export GIO_USE_VOLUME_MONITOR="unix"

if [ -r "${HOME}/.xprofile" ]; then
    . "${HOME}/.xprofile"
fi

if command -v clawdie-live-touchpad-guard >/dev/null 2>&1; then
    echo "Starting touchpad guard"
    clawdie-live-touchpad-guard &
fi

if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
    echo "Starting session under dbus-run-session"
    exec dbus-run-session -- /usr/local/bin/clawdie-xfce-session-inner
fi

echo "Starting session without dbus-run-session fallback"
exec /usr/local/bin/clawdie-xfce-session-inner
