#!/bin/bash
# Applies Das OS per-user defaults that cannot be shipped as static xfconf files.
# xfdesktop keys wallpapers by monitor connector name (eDP-1, HDMI-1, Virtual-1...),
# which is only known inside the session. Runs once per user.
set -u

marker="${XDG_CONFIG_HOME:-$HOME/.config}/das/session-init.done"
[[ -e $marker ]] && exit 0

wallpaper=/usr/share/backgrounds/das/das-light.svg
if [[ $(xfconf-query -c xsettings -p /Net/ThemeName 2>/dev/null) == *-Dark ]]; then
  wallpaper=/usr/share/backgrounds/das/das-dark.svg
fi

# Sets an xfconf property, creating it when it does not exist yet.
set_prop() {
  local prop=$1 type=$2 value=$3
  xfconf-query -c xfce4-desktop -p "$prop" -s "$value" 2>/dev/null ||
    xfconf-query -c xfce4-desktop -p "$prop" -n -t "$type" -s "$value"
}

# "xrandr --listactivemonitors" prints a header, then one line per monitor ending in its connector name.
monitors=$(xrandr --listactivemonitors 2>/dev/null | awk 'NR > 1 { print $NF }')
if [[ -z $monitors ]]; then
  echo "das-session-init: no active monitors found, will retry at next login" >&2
  exit 1
fi

for monitor in $monitors; do
  base="/backdrop/screen0/monitor${monitor}/workspace0"
  set_prop "$base/last-image" string "$wallpaper"
  set_prop "$base/image-style" int 5 # zoomed: fill the screen, keep proportions
done

mkdir -p "${marker%/*}" && touch "$marker"
