#!/usr/bin/env bash

# Original script steal from (specific commit):
# https://github.com/lime-desu/dootsfile/blob/58abca63dfd596d4812fcf95567cc3ad63ffbb6f/scripts/set-random-wallpaper.sh

WALLPAPER_DIR=${HOME}/Drives/Stuff/Pictures/Waifus
WALLPAPER_PREFIX="Fondos_PC.*"
RANDOM_PICTURE=$(fd -apt f "$WALLPAPER_PREFIX" "$WALLPAPER_DIR" | shuf -n 1)
CURRENT_DESKTOP="$(echo "$XDG_CURRENT_DESKTOP" | awk '{for (i=1;i<=NF;i++) { $i=toupper(substr($i,1,1)) tolower(substr($i,2)) }}1')"

# Extra actions
declare -A CONFIG
CONFIG["delete_current"]=false

show_help() {
	echo -e "${BLD}Usage: ${GRN}set-random-wallpaper${RST}${YLW} [OPTION]${RST}"
	echo -e ""
	echo -e "${BLD}  Options:${RST}"
	echo -e "${YLW}    -d, delete      ${RST}delete current wallpaper"
	echo -e "${YLW}    -h, --help      ${RST}Show this help"
}

case "$1" in
delete | -d)
	CONFIG["delete_current"]=true
	;;
help | -h)
	show_help
	;;
*) ;;
esac

shift

case "$CURRENT_DESKTOP" in
Gnome)

	if [[ "${CONFIG[delete_current]}" == true ]]; then
		file_path="$(gsettings get org.gnome.desktop.background picture-uri)"
		file_path="${file_path:8:-1}"

		rm -iv "$file_path"
	fi

	gsettings set org.gnome.desktop.background picture-uri "file://$RANDOM_PICTURE"
	gsettings set org.gnome.desktop.background picture-uri-dark "file://$RANDOM_PICTURE"
	;;
Xfce)
	backdrop=$(xfconf-query --channel xfce4-desktop --property /backdrop --list | grep -E -e "screen.*/monitor.*image-path$" -e "screen.*/monitor.*/last-image$")
	for i in ${backdrop}; do
		xfconf-query --channel xfce4-desktop --property "$i" --create --type string --set "$RANDOM_PICTURE"
		xfconf-query --channel xfce4-desktop --property "$i" --set "$RANDOM_PICTURE"
	done
	;;
KDE)
	export DISPLAY=:0
	kwriteconfig5 --file kdeglobals --group Wallpaper --key Picture "$RANDOM_PICTURE"
	qdbus org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.evaluateScript '
        var allDesktops = desktops();
        print (allDesktops);
        for (i=0;i<allDesktops.length;i++) {{
            d = allDesktops[i];
            d.wallpaperPlugin = "org.kde.image";
            d.currentConfigGroup = Array("Wallpaper","org.kde.image","General");
            d.writeConfig("Image", "file:///'$RANDOM_PICTURE'")
        }}
        '
	;;
Sway)
	MODES=(
		[bg - center]=center
		[bg - fill]=fill
		[bg - max]=fit
		[bg - scale]=stretch
		[bg - tile]=tile
	)
	# default to fill if there's no bgtypes
	BGTYPE=${BGTYPE:fill}
	MODE=${MODES[$BGTYPE]}
	swaymsg output "*" bg "$WALLPAPER" "$MODE"
	;;
i3)
	if command -v feh >/dev/null; then
		feh --bg-scale "$RANDOM_PICTURE"
	elif command -v nitrogen >/dev/null; then
		nitrogen --set-scaled "$RANDOM_PICTURE"
	fi
	;;
*)
	notify-send "Error: $(basename "$0")" "This script does not support $CURRENT_DESKTOP."
	exit 1
	;;
esac

if [[ "$CURRENT_DESKTOP" =~ ^(Gnome|Xfce|KDE|Sway|i3)$ ]]; then
	display_path="$(echo "$RANDOM_PICTURE" | awk -F '/' '{print "(...)/"$(NF-1)"/"$NF}')"
	notify-send 'Wallpaper changed:' "$display_path"
fi
