#!/bin/dash
# Background wallpaper slideshow.
# Don't run this script directly. Instead start/stop a slideshow from
# the File menu of the Wallpaper Setter, cf. "wallpaper --help".

MAX_CONSECUTIVE_ERRORS=10

[ -z "${USRDIR}" ] && USRDIR="${HOME}/.config/wallpaper"

# source SLIDEDIR, INT and RANDOM_IMAGE settings
. "${USRDIR}/preferences"
[ "${RANDOM_IMAGE}" = true ] && shuffle=${SHUFFLE:-shuf}

# mode ::= 'Centre'|'Scale'|'Tile'|'Stretch'|'Distort'
# $1 ::= [[mode':']image-dir-path] | playlist-file-path
MODE=${1%:*}; idp=${1#*:}; [ "${MODE}" = "${idp}" ] && MODE=

DIR="${idp:-$SLIDEDIR}"
[ -z "$DIR" ] && DIR=/usr/share/backgrounds
SHOW="${USRDIR}/slideshow"
# cases:
# /usr/bin/wallpaper -play => $APPDIR/slideshow -start
# /usr/bin/wallpaper -play-dir=$1  => $APPDIR/slideshow -start-dir=$1
if [ -d "${DIR}" ]; then
  # Try filling MODE value from file backgroundmode, if it exists
  if [ -z "${MODE}" -a -s "${USRDIR}/backgroundmode" ]; then
    read MODE < "${USRDIR}/backgroundmode"
  fi
  find -H "${DIR}" -type f | grep -i -E "\.(jpg|jpeg|png|gif|tiff?|bmp|svg)$" > "${SHOW}"
else
  # $1 ::= playlist-file-path
  # cases:
  # /usr/bin/wallpaper -play-list=$1 => $APPDIR/slideshow -start-list=$1
  cp -f "$1" "${SHOW}"
fi
if which $shuffle >/dev/null 2>&1; then
  $shuffle "${SHOW}" > "${SHOW}.tmp"
  mv -f "${SHOW}.tmp" "${SHOW}"
fi

# begin loop
first_iter=true consecutive_errors=0
test -s "$SHOW" && while :;
do
  while read IMG; do
    # re-source the preferences file in case the interval has changed
    . "${USRDIR}/preferences"

    # re-source background mode in case it has changed
    case ${IMG} in
      *:*) # explicit mode, no re-sourcing needed
        MODE=${IMG%:*}; ifp=${IMG#*:}; [ "${MODE}" = "${ifp}" ] && MODE= ;;
      *) # implicit mode, do re-sourcing except on first iteration
        ifp=$IMG
        [ -z "${first_iter}" -a -s "${USRDIR}/backgroundmode" ] &&
          read MODE < "${USRDIR}/backgroundmode"
    esac

    # Change desktop background.
    # was [/usr/bin/]wallpaper "$IMG"
    export ACTIVE_SLIDESHOW_INT=${INT:-15} # signal set_bg
    if "${APPDIR:-/usr/local/apps/Wallpaper}/AppRun" \
      "${MODE:-Centre}:${ifp}"
    then # sleep iff success on changing background
      consecutive_errors=0
      first_iter= # enable reading backgroundmode
      sleep ${INT:-15}
    else
      consecutive_errors=$((consecutive_errors +1))
      [ $consecutive_errors -gt $MAX_CONSECUTIVE_ERRORS ] && exit 1
    fi
  done < "${SHOW}"
done

