#!/bin/env bash

if [ -f "$HOME/.profile" ]; then
	source "$HOME/.profile"
fi

monitor=($(xrandr | awk -v name="$1" '$1 == name && $2 == "connected" {
	for(i=1;i<=NF;i++) {
		if($i ~ /[0-9]+x[0-9]+\+[0-9]+\+[0-9]+/) {
			split($i, a, /[+x]/); print $1 " " a[1] " " a[2]; exit
		}
	}
}'))
monitor_name="${monitor[0]}"
monitor_width="${monitor[1]}"
monitor_height="${monitor[2]}"
prop="/backdrop/screen0/monitor${monitor_name}/workspace0/last-image"

path="$2"
wallpaper_dir="$HOME/.local/share/le_wallpaper"
wallpaper_path="${wallpaper_dir}/.${monitor_name}.png"
wallpaper_store="${wallpaper_dir}/${monitor_name}_path"

mkdir -p "$wallpaper_dir"

if [ -z "$path" ]; then
	path="$(xfconf-query -c xfce4-desktop -p "$prop")"
	
	if [[ ! "$path" = /* ]]; then
		path="${HOME}/${path}"
	fi
fi

if [ "$path" == "$wallpaper_path" ]; then
	path=$(cat "$wallpaper_store")
fi

# path="$(readlink -f "$path")"

if [ ! -f "$path" ]; then
	echo "No wallpaper source"
	exit 0
fi

filename=$(basename -- "$path")
ext="${filename##*.}"

# The following always assumes the monitor is landscape
if [ "$ext" == "svg" ] && command -v inkscape; then
	tmp="$(mktemp).png"
	inkscape -h "$monitor_height" "$path" -o "$tmp"
	path="$tmp"
fi

export SCHEME
shchemes create_theme imagemagick \
	| convert "$path" -colorspace srgb -dither FloydSteinberg -geometry "${monitor_width}x" -remap txt:- "$wallpaper_path"

echo "Setting wallpaper: $path"
xfconf-query -c xfce4-desktop -p "$prop" -s "$wallpaper_path"
echo "$path" > "$wallpaper_store"

le-wallpaper-open
