#!/bin/bash

# set sane defaults
[ -z "$wallpaper_sleep_for" ] && wallpaper_sleep_for="180"
[ -z "$wallpaper_path" ] && wallpaper_path="$(xdg-user-dir PICTURES)/wallpaper"
mkdir -p "$wallpaper_path"

# validate wallpaper path
[ $(find "$wallpaper_path" -type f | wc -l) -gt 0 ] || exit 1

# there can be only one
while [ $(ps aux | grep -v 'grep' | grep -c "$0") -gt 2 ]; do
	kill $(ps aux | grep -v 'grep' | grep -v $$ | grep "$0" | awk '{print $2}') &> /dev/null
done

# infinitely change wallpaper
while true; do
	old_pid=$(ps aux | grep swaybg | awk 'NR==1{ print $2 }')
	swaybg_cmd="swaybg"
	sway_outputs=( $(swaymsg -t get_outputs | jq -r '.[].name') )
	for op in "${sway_outputs[@]}"; do
		wp=$(printf '%q' "$(find $wallpaper_path -type f | sort -R | tail -1)")
		swaybg_cmd="${swaybg_cmd} -o $op -i $wp -m fit -c \#000000"
	done
	eval $swaybg_cmd &
	sleep 1
	[ -n "$old_pid" ] && kill $old_pid 2>/dev/null
	sleep $wallpaper_sleep_for
done
