#!/usr/bin/env bash

if [ $# -ne 2 ];then
	echo -n "Usage: $0 directory_name timeout_in_seconds
	Leave the directory name blank for Current Directory
	For you lazy pal, I assume timeout as 5 sec and Directory as current
	Do you want to accept this settings? (Y/n): ";
	read response
	if [[ "$response" =~ ^[^yY] ]];then
		exit 0
	fi
fi

function set_wallpaper(){
	gconftool-2 -s /desktop/gnome/background/picture_options "centered" -t string;
	gconftool-2 -s /desktop/gnome/background/picture_filename "$1" -t string;
}
		
TIMEOUT=${2-5};
WALL_DIR=${1-`pwd`};

echo "Timeout value is: $TIMEOUT";
echo "Directory is: $WALL_DIR";
echo 

if [ ! -d "$WALL_DIR" ];then
	echo "The Directory Specified is invalid..";
	exit 1;
fi

filelst="$(find "$WALL_DIR" -type f -name '*.jpg' -o -name '*.png')";
if [ -z "$filelst" ];then
	echo "No Suitable files found in this location: $WALL_DIR";
	exit 1;
fi

while true;do
	filename=`echo "$filelst" | shuf -n 1`
	set_wallpaper "$filename";
	sleep $TIMEOUT;
done
exit 0