#!/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
	wallpaper_cmd="feh --no-fehbg"
	monitor_count=$(xrandr -d :0 -q | grep -c " connected")
	while [ $monitor_count -gt 0 ]; do
		wallpaper_cmd="$wallpaper_cmd --bg-max \"$(find $wallpaper_path -type f | sort -R | tail -1)\""
		let monitor_count=monitor_count-1
	done
	eval "$wallpaper_cmd"
	sleep $wallpaper_sleep_for
done
