#!/bin/bash

FLAG_FILE="${HOME}/.config/basalt-wallpaper-setup.done"
WALLPAPER="/usr/share/backgrounds/basalt-desktop-4.jpg"

[ -f "$FLAG_FILE" ] && exit 0

# Wait for xfdesktop to be ready (channel must exist)
for i in 1 2 3 4 5; do
    xfconf-query -c xfce4-desktop -p /backdrop -l 2>/dev/null | grep -q . && break
    sleep 2
done

# Set backdrop image for all connected monitors
MONITORS=$(xrandr --query 2>/dev/null | awk '/ connected/{print $1}')
if [ -z "$MONITORS" ]; then
    # Fallback: no xrandr (Wayland or headless) — set last-image directly
    xfconf-query -c xfce4-desktop \
        -p "/backdrop/screen0/monitor0/workspace0/last-image" \
        -s "$WALLPAPER" -t string --create 2>/dev/null || true
else
    for MONITOR in $MONITORS; do
        for ((w=0; w<4; w++)); do
            xfconf-query -c xfce4-desktop \
                -p "/backdrop/screen0/monitor${MONITOR}/workspace${w}/last-image" \
                -s "$WALLPAPER" -t string --create 2>/dev/null || true
            xfconf-query -c xfce4-desktop \
                -p "/backdrop/screen0/monitor${MONITOR}/workspace${w}/image-style" \
                -s 5 -t int --create 2>/dev/null || true
        done
        xfconf-query -c xfce4-desktop \
            -p "/backdrop/screen0/monitor${MONITOR}/image-path" \
            -s "$WALLPAPER" -t string --create 2>/dev/null || true
    done
fi

# Also set workspace0 fallback under screen0
xfconf-query -c xfce4-desktop \
    -p "/backdrop/screen0/workspace0/last-image" \
    -s "$WALLPAPER" -t string --create 2>/dev/null || true

mkdir -p "$(dirname "$FLAG_FILE")"
touch "$FLAG_FILE"
