#!/bin/bash

. /usr/local/lib/desktop-session/lib-desktop-session.sh

random_select() {
    wallpaper_folder="$(cat $wallpaper_conf | grep '^FOLDER' |cut -d '=' -f2 |cut -d " " -f2)";
    alist=( $(ls -w1 $wallpaper_folder ) );
    range=${#alist[*]};
    show=$(( $RANDOM % $range ));
    file=""$wallpapers/${alist[$show]}"";
    wallpaper=""$wallpaper_folder""$file"";
    sedfile=${wallpaper//\//\\\/};
    sed -i "s/^$code=.*/$code=$sedfile/" $wallpaper_list_conf;
}

wallpaper_set() {
    
    wallpaper=${wallpaper:-$(cat $wallpaper_list_conf | grep "^$code" |cut -d '=' -f2 )} #|sed "s/\ /\\\ /ig")}
    
    case $im in
        rox)
            Rox-Wallpaper "$wallpaper" &
            feh --bg-$style "$wallpaper" &
            ;;
        space)
            spacefm --set-wallpaper "$wallpaper" &
            feh  --bg-$style "$wallpaper" &
            ;;
        *)
            feh  --bg-$style "$wallpaper" &
            ;;
    esac
}

#######START########
IFS='
'
disp=${DISPLAY#:}
disp=${disp%.[0-9]}
conf_dir="$HOME/.desktop-session"
wallpaper_conf="$conf_dir/wallpaper.conf"
wallpaper_list_conf="$conf_dir/wallpaper-list.conf"
if [ ! -f "$wallpaper_conf" ]; then
    wallpaper_conf="/etc/desktop-session/wallpaper.conf"
fi
if [ ! -f "$wallpaper_list_conf" ]; then
    wallpaper_conf="/etc/desktop-session/wallpaper-list.conf"
fi

type="$(cat $wallpaper_conf | grep '^TYPE' |cut -d '=' -f2 |cut -d ' ' -f2)"
style="$(cat $wallpaper_conf | grep '^STYLE' |cut -d '=' -f2 |cut -d ' ' -f2)"
delay="$(cat $wallpaper_conf | grep '^DELAY' |cut -d '=' -f2 |cut -d ' ' -f2)"
code=${1:-$(cat $conf_dir/desktop-code.$disp)}
wm=${code#*-}
im=${code%-$wm}

case "$type" in
    random)
        random_select
        wallpaper_set 
        ;;
        
    random-time)
        yad --notification --command="killall 'desktop-session-wallpaper' 'yad'" --text="click this icon to kill random wallpaper timed" --image="wallpaper" & pid1="$!"
        while true; do
            random_select
            wallpaper_set 
            sleep $delay
        done
        ;;
        
    static)
        wallpaper_set 
        ;;
        
    color)
        imported_color=$(cat $wallpaper_conf | grep '^COLOR' |cut -d '=' -f2 |cut -d ' ' -f2)
        xsetroot -solid "#$imported_color" &
        ;;

    *)
        say "There was no valid style for wallpaper setting found, defaulting to grey background";
        xsetroot -solid "#8a8a8a";
        ;;
esac
