#!/bin/bash

Dir="/home/n/img/wallpap/1920x1200/"
wallpaplist="/home/n/.wallpaplist"

if [ ! -d "$Dir" ];
then
    echo "${Dir} does not exist"
    exit 1
fi

if [ ! -f ${wallpaplist} ];
then
        touch ${wallpaplist}
fi

AvailableFiles=`ls -1 ${Dir} | wc -l`
AlreadyViewedFiles=`cat ${wallpaplist} | wc -l`

TotalFiles=`expr $AvailableFiles - $AlreadyViewedFiles`

if [ $TotalFiles -lt 1 ];
then
        echo "*** Seems we have displayed all available wallpapers; let's do the time warp...again. ***"
        rm -f ${wallpaplist}
        TotalFiles=$AvailableFiles
fi

RandomNumber=$(( $RANDOM % $TotalFiles ))
test ! $RandomNumber = 0 || RandomNumber=1

RandomFile="$( ls -1 ${Dir} | grep -w -v -F -f ${wallpaplist} | head -n $RandomNumber | tail -n 1)"
if [[ ${RandomFile} == "" ]];
then
        echo "*** Oops, something went wrong. erasing cache for security ***"
        rm -f ${wallpaplist}
        exit 1
else
        echo "${RandomFile}" >> ${wallpaplist}
fi


#echo "Selected File: $RandomFile"
DISPLAY=:0.0 feh --bg-scale "${Dir%/}/${RandomFile}"
DISPLAY=:0.0 xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s "${Dir%/}/${RandomFile}"
feh --bg-scale "${Dir%/}/${RandomFile}"
xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s "${Dir%/}/${RandomFile}"
pkill gkrellm && DISPLAY=:0.0 gkrellm
