#!/bin/bash

    # This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.

    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    # GNU General Public License for more details.

    # You should have received a copy of the GNU General Public License
    # along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Simple Background - sbg.  A script to set the wallpaper in my custom
# BSPWM session, as well as supported GTK-based desktop environments.
# This script is part of my dotfiles:
# https://gitlab.com/protesilaos/dotfiles

# TODO is "Pictures" automatically localised?
# TODO ~/.config/user-dirs.dirs seems to contain environment variables…

sbg_do() {
	# find the path to the input file
	local picture="$(readlink -fn $1)"

	# Make sure this is an image file
	if [[ $picture =~ .*\.(jpg|jpeg|png) ]]; then
		echo "This is a valid image file"
	else
		echo "ERROR. This is not a valid image file."
		echo "Aborting..."
		exit 1
	fi

	case "$DESKTOP_SESSION" in
		bspwm)
			# NOTE there is no standard way for defining a wallpaper in
			# BSPWM.  Using a hidden file from the home dir is specific
			# to my custom desktop session.
			#
			# Copy the selected image to the home directory, as a hidden
			# file.
			#
			# Dependency on Debian Buster:
			# 	sudo apt install feh
			cp -f "$picture" "$HOME/.wallpaper.jpg"
			feh --bg-fill "$HOME/.wallpaper.jpg"
			;;
		gnome)
			gsettings set org.gnome.desktop.background picture-uri "file://$picture"
			;;
		mate)
			gsettings set org.mate.background picture-filename "$picture"
			;;
		xfce)
			# TODO any way to define a wallpaper in Xfce without
			# specifying screen, monitor, workspace?
			xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s "$picture"
			;;
		*)
			echo "ERROR. Unknown Desktop Session."
			echo "Cannot set wallpaper."
			echo "Aborting..."
			exit 1
			;;
	esac

	echo "Changing wallpaper to $picture"
}

# Run the script
sbg_do $1
