#!/bin/sh
# Re-apply the live USB no-blank policy after XFCE components start.
# Xorg ServerFlags and ~/.xprofile set the baseline, but xfsettingsd /
# xfce4-power-manager can re-assert per-user display power settings later in
# session startup. This guard makes the policy explicit at the desktop level.

_uid="$(id -u 2>/dev/null || echo unknown)"
_runtime_dir="${XDG_RUNTIME_DIR:-${HOME}/.cache/clawdie/runtime}"
mkdir -p "${_runtime_dir}" 2>/dev/null || true
_lock="${_runtime_dir}/clawdie-noblank-guard.${_uid}.lock"
_log="${HOME}/.clawdie-noblank-guard.log"

if ! mkdir "${_lock}" 2>/dev/null; then
    exit 0
fi
trap 'rmdir "${_lock}" 2>/dev/null || true' EXIT HUP INT TERM

log()
{
    printf '%s %s\n' "$(date '+%H:%M:%S')" "$*" >> "${_log}" 2>/dev/null || true
}

apply_xset()
{
    [ -n "${DISPLAY:-}" ] || return 0
    xset s off 2>/dev/null || true
    xset -dpms 2>/dev/null || true
    xset s noblank 2>/dev/null || true
}

set_xfconf()
{
    _property="$1"
    _type="$2"
    _value="$3"

    command -v xfconf-query >/dev/null 2>&1 || return 0
    xfconf-query -c xfce4-power-manager -p "${_property}" -n -t "${_type}" -s "${_value}" >/dev/null 2>&1 || \
        xfconf-query -c xfce4-power-manager -p "${_property}" -s "${_value}" >/dev/null 2>&1 || true
}

apply_xfce_power_policy()
{
    # Disable display blanking, DPMS and idle suspend in xfce4-power-manager.
    # Keep this in sync with panel-skel xfce4-power-manager.xml.
    set_xfconf /xfce4-power-manager/blank-on-ac int 0
    set_xfconf /xfce4-power-manager/blank-on-battery int 0
    set_xfconf /xfce4-power-manager/dpms-enabled bool false
    set_xfconf /xfce4-power-manager/dpms-on-ac-sleep int 0
    set_xfconf /xfce4-power-manager/dpms-on-ac-off int 0
    set_xfconf /xfce4-power-manager/dpms-on-battery-sleep int 0
    set_xfconf /xfce4-power-manager/dpms-on-battery-off int 0
    set_xfconf /xfce4-power-manager/inactivity-on-ac int 0
    set_xfconf /xfce4-power-manager/inactivity-on-battery int 0
    set_xfconf /xfce4-power-manager/lock-screen-suspend-hibernate bool false
    set_xfconf /xfce4-power-manager/presentation-mode bool true
}

log "starting no-blank guard"
apply_xfce_power_policy
apply_xset

# Re-apply through the noisy part of XFCE startup, when xfsettingsd or
# xfce4-power-manager may appear after ~/.xprofile has already run.
for _i in 1 2 3 4 5 6 7 8 9 10 11 12; do
    sleep 10
    apply_xfce_power_policy
    apply_xset
done

log "finished no-blank guard"
exit 0
