#!/usr/bin/env bash

# This script is run when the application starts
# Its purpose is to obtain the current wallpaper as an absolute path, or file URI (e.g. file://a/b.jpg)
# This is needed by Variety at start to ensure History->Back works OK to revert back to the pre-Variety wallpaper.

desktop="$DESKTOP_SESSION"

# Gnome 3, Unity:
if [ "$desktop" == "ubuntu" ] || [ "$XDG_CURRENT_DESKTOP" == "Unity" ] || [ "$XDG_CURRENT_DESKTOP" == "Budgie" ]; then
        gsettings get org.gnome.desktop.background picture-uri

# XFCE
elif [ "$desktop" == "xubuntu" ] || [ "$XDG_CURRENT_DESKTOP" == "XFCE" ]; then
        # Find first existing backdrop property (monitor names vary by setup)
        # See: https://github.com/varietywalls/variety/issues/164
        prop=$(xfconf-query -c xfce4-desktop -p /backdrop -l 2>/dev/null | grep -E -e "screen.*/monitor.*/last-image$" -e "screen.*/monitor.*image-path$" | head -1)
        if [ -n "$prop" ]; then
                xfconf-query -c xfce4-desktop -p "$prop" 2>/dev/null
        fi

# Lingmo OS
elif [ "$XDG_CURRENT_DESKTOP" == "Lingmo" ]; then
        qdbus com.lingmo.Settings /Theme com.lingmo.Theme.wallpaper

# LXDE/PCManFM
elif [ "$XDG_CURRENT_DESKTOP" == "LXDE" ]; then
        # The PCManFM config path varies by session name; Lubuntu is effectively a special case here
        if [ "$desktop" == "Lubuntu" ]; then
            desktop="lubuntu"  # Curse this inconsistency in cases
        fi
        grep wallpaper=/ "$HOME/.config/pcmanfm/$desktop/desktop-items-0.conf" | sed -e 's/wallpaper=//g'

# LXQt/PCmanFM-qt
elif [ "$XDG_CURRENT_DESKTOP" == "LXQt" ]; then
        grep wallpaper=/ ~/.config/pcmanfm-qt/lxqt/settings.conf | sed -e 's/wallpaper=//g'

# MATE
elif [ "$XDG_CURRENT_DESKTOP" == "MATE" ]; then
        gsettings get org.mate.background picture-filename

# Cinnamon after 2.0
elif [ "$desktop" == "Cinnamon" ] || [ "$XDG_CURRENT_DESKTOP" == "X-Cinnamon" ]; then
        gsettings get org.cinnamon.desktop.background picture-uri

# KDE Plasma 5+
elif [ "$XDG_CURRENT_DESKTOP" == "KDE" ]; then
        grep 'Image=' ~/.config/plasma-org.kde.plasma.desktop-appletsrc | sed 's/Image=//'

# Trinity
elif [ "$XDG_CURRENT_DESKTOP" == "Trinity" ]; then
        # The "1" refers to the virtual desktop number
        dcop kdesktop KBackgroundIface currentWallpaper 1 2> /dev/null

# Cosmic
elif [ "$XDG_CURRENT_DESKTOP" == "COSMIC" ]; then
        grep -oP '(?<=source: Path\(")(.+)(?="\))' ~/.config/cosmic/com.system76.CosmicBackground/v1/all

# All above fails => fallback to the Gnome 3 way
else
        gsettings get org.gnome.desktop.background picture-uri
fi

# Feh
# sed "s/\ /\n/g" ~/.fehbg | grep \'

# Gnome 2
# gconftool-2 --get /desktop/gnome/background/picture_filename
