#!/bin/sh

# Copyright (C) 2008 Tomas Åkesson <tomas@entropic.se>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Will use the program "feh" to set wallpaper by default. Change it if you wan't
# to use some other app. Or just use the -kde or -gnome options.
SETBG="feh"
#SETBG="~/bin/setbackground.py"
#SETBG="fvwm-root"   # can not display jpg-images

SETBG_POST_OPTS="" # If the setbg-command needs options/args after the image name

DEBUG="0"
NOTREALLY="0"
IFS='
'
DIRLIST=""

# Parse parameters
while test -n "$1" ; do
    case "$1" in
        -debug)
            DEBUG="1"
            shift
            ;;
        -n)
            NOTREALLY="1"
            shift
            ;;
        -gnome)
            SETBG="gconftool -t string -s /desktop/gnome/background/picture_filename"
            shift
            ;;
        -kde)
            # dcop kdesktop KBackgroundIface setWallpaper /path/to/a/file.jpg n
            # n is:
            # 0 nothing
            # 1 centered
            # 2 tiled
            # 3-6 modes I don't use :)
            # 7 downscaled but not upscaled
            SETBG="dcop kdesktop KBackgroundIface setWallpaper"
            SETBG_POST_OPTS="7" # downscaled but not upscaled
            SETBG_OPTS=""
            shift
            ;;
        *)
            if test -d "$1" ; then
                f="$(realpath $1)"
                DIRLIST="${DIRLIST}${IFS}${f}"
            elif test -f "$1" ; then
                f="$(realpath $1)"
                DIRLIST="${DIRLIST}${IFS}${f}"
            else
                echo "randombg: Invalid file/directory: $1"
            fi
            shift
            ;;
    esac
done

if [ -z "${DIRLIST}" ] ; then
    echo "randombg: No args or invalid args."
    exit 10
fi


# Set specific options for different image viewers
case "$SETBG" in
    feh)
        # LAST_BG is not working yet, so don't use it!
        LAST_BG="$(test -f ~/.fehbg && cat ~/.fehbg)"
        SETBG_OPTS="--bg-center"
        ;;
    fvwm-root)
        LAST_BG=""
        SETBG_OPTS="-r"
        ;;
    *)
        LAST_BG=""
        SETBG_OPTS=""
esac



# Find images and sort them according to access-time (latest access last), then
# cut off the last entries to prevent them to show again too soon.
if [ "$DEBUG" = "1" ] ; then
    find 2>/dev/null ${DIRLIST} -follow -type f -printf '%C@ %C+ %p\n' | \
        egrep -i '^.*(gif|png|jpg|jpeg)$' | \
        sort -n
fi

num_items=$(find 2>/dev/null ${DIRLIST} -follow -type f -printf '%C@ %p\n' | \
    egrep -i '^.*(gif|png|jpg|jpeg)$' | \
    sort -n | cut -d ' ' -f 2- | \
    wc -l)
items_saved=$(expr "$num_items" / 5)
cutoff=$(expr "$num_items" - "$items_saved")

# If items_saved is 0, then set it to 1, so at least one entry is saved.
if test "$items_saved" -eq 0 ; then
    test "$DEBUG" = "1" && \
        echo "randombg: Setting items_saved to 1"
    items_saved="1"
fi


test "$DEBUG" = "1" && \
    echo "randombg: items: $num_items, cutoff: $cutoff, saved: $items_saved"

# Randomize the items
item=$(find 2>/dev/null ${DIRLIST} -follow -type f -printf '%C@ %p\n' | \
    egrep -i '^.*\.(gif|png|jpg|jpeg)$' | \
    sort -n | cut -d ' ' -f 2- | \
    head -${items_saved} | \
    perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;')

if test "$DEBUG" = "1" ; then
    echo "randombg: Items discarded:"
    find 2>/dev/null ${DIRLIST} -follow -type f -printf '%C@ %p\n' | \
        egrep -i '^.*\.(gif|png|jpg|jpeg)$' | \
        sort -n | cut -d ' ' -f 2- | \
        tail -${cutoff}
    echo " "
fi
if test "$DEBUG" = "1" ; then
    echo "randombg: Items saved:"
    find 2>/dev/null ${DIRLIST} -follow -type f -printf '%C@ %p\n' | \
        egrep -i '^.*\.(gif|png|jpg|jpeg)$' | \
        sort -n | cut -d ' ' -f 2- | \
        head -${items_saved}
    echo " "
fi

if test -z "$item" ; then
    echo "randombg: No images found"
    exit 0
fi

test "$DEBUG" = "1" && \
    echo "randombg: Using image $item"


# Touch the file so it is sorted last on the next run
if [ "$NOTREALLY" = "0" ] ; then
    touch -c "$item"
    eval $SETBG $SETBG_OPTS \"$item\" $SETBG_POST_OPTS
fi
