#!/bin/dash
#150503 step: see https://github.com/step-/nathans-wallpaper/

#|set +x
#|echo     " >&2
#|---------- set_bg $(date)"
#|set -x

# We assume that rox is already running for $USER. If not, on its first
# invocation for $USER rox will
# 1) complain that it can't find dir ~/.icons to set link ~/.icons/ROX
# 2) daemonize and keep gtkdialog's parent process active after gtkdialog has closed.
# Note that Wallpaper Setter AppRun actually tests for a running ROX-Filer process.

# Determine the path to this application.
APPDIR=${0%/*}; APPDIR=`cd "$APPDIR";pwd`

DEBUG=${DEBUG:-} # unset to disable debug trace to stderr; set verbosity (integer) 1-3
CACHEROOT=${CACHEROOT:-/usr/share/backgrounds}

# Emit pathname of current wallpaper preview file
get_current_preview()
{
  local PREVIEWIMG=/tmp/$USER-current_wallpaper_selection.jpg
  local prw="$(readlink -e "${PREVIEWIMG}")" # keep readlink !
  [ -n "${prw}" ] && echo -n "${prw}"
}

set +f
mkdir -p ${HOME}/.config/wallpaper "$CACHEROOT"
if [ "$1" = "-clear" ];then
 [ "${DEBUG}" ] && set -x
 x=$HOME/.config/rox.sourceforge.net/ROX-Filer
 y=$HOME/.config/wallpaper
 [ -e $x/pb_default -a $x/PuppyPin -ot $x/pb_default ] && z=$x/pb_default || z=$x/PuppyPin
 grep -v '<backdrop' $z > $y/pb &&
 mv -f $y/pb $x/pb_default &&
 rox -p $x/pb_default
 # remove cached copies of the actual background wallpaper
 if read x < $y/bg_img; then
  x=${x##*/}
  rm -f "$CACHEROOT"/.[0-9]*/"$x"
 fi
 # remove cached copies of the current preview wallpaper
 x=$(get_current_preview)
 x=${x##*/}; x=${x%.jpg}
 rm -f "$CACHEROOT"/.[0-9]*/"$x" "$CACHEROOT"/.[0-9]*/"$x.jpg";
 # remove current preview image (file or link)
 rm -f "$CACHEROOT/.preview/$x.jpg" "$CACHEROOT/.preview/$x.jpg.jpg"

 echo "[none]" > $y/bg_img
 [ "${DEBUG}" ] && set +x
 exit
fi

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

# accept non-empty image file only
[ -s "${ifp}" ] || exit 1 # -z=!-n < -f < -s

if [ -z "${MODE}" ]; then
  [ ! -s ${HOME}/.config/wallpaper/backgroundmode ] &&
    echo Centre > ${HOME}/.config/wallpaper/backgroundmode # sensible catchall
  read MODE < ${HOME}/.config/wallpaper/backgroundmode
fi
# convert MODE to UK-spelling infinitive verb for rox --RPC
case $MODE in
 Scale*) MODE=Scale  ;;
 Stretch*) MODE=Stretch ;;
 Tile*) MODE=Tile ;;
 Center*|Centre*|*) MODE=Centre ;; # sensible catchall
esac

# Windows BMP support
bmptojpg () # $1-bmp-image-path
{
  local name out
  name=${1##*/}; name=${name%.*}
  out="$CACHEROOT/${name}.jpg"
  # Convert BMP $1 to JPG $out. Notice that we don't overwrite an
  # existing, non-empty $out.  So if $out already exists before we get
  # called we will wrongly return it as the converted $out.  Since the
  # latter case is very unlikely we ignore it.
  [ ! -s "${out}" ] && bmptopnm "$1" | pnmtojpeg -quality=85 > "${out}"
  [ -s "${out}" ] && echo -n "${out}" # signal success
}

#20150503 ROX-Filer can't convert BMP, so we do it here
case ${ifp} in *.bmp|*.BMP) NEWIMAGE=$(bmptojpg "${ifp}");; *) NEWIMAGE= ;; esac
# NEWIMAGE is non-null iff conversion succeeded

#w482 BK now have script that truncates an image vertically so that it has the right dimensions
#for a widescreen...
#140101 background_reshape has changed...
[ -z "${NEWIMAGE}" ] && NEWIMAGE="${ifp}"
if [ "$MODE" = "Stretch" ]; then
 #truncated image is created, in a sub-directory of $CACHEROOT, ex: /usr/share/backgrounds/.177/image.jpg
 # where "177" is the screen aspect ratio, as a percentage.
 [ "${DEBUG}" ] && echo >&2 "========== set_bg calls ${APPDIR}/background_reshape" "${NEWIMAGE}"
 DEBUG=${DEBUG} \
 SCALE_FILTER=${SCALE_FILTER} \
 "${APPDIR}/background_reshape" "${NEWIMAGE}"
 RETVAL=$?
 if [ $RETVAL -eq 10 -o $RETVAL -eq 11 ];then # legacy compatibility
  read NEWIMAGE < /tmp/$USER-qwallpaper_reshaped
 else
  exit 1 # exit without changing background on reshaping error
 fi
fi

if which rox >/dev/null 2>&1; then
# Tell rox to use a new background image.
# Note this will also write to ${HOME}/Choices/ROX-Filer/PuppyPin.
# Careful! If ROX-Filer doesn't grok the $NEWIMAGE file type it will actually
# delete $NEWIMAGE (with a dialog window that says 'removing the backdrop').
 rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <SetBackdrop>
   <Filename><![CDATA[${NEWIMAGE}]]></Filename>
   <Style>${MODE}</Style>
  </SetBackdrop>
 </env:Body>
</env:Envelope>

EOF
 echo "${NEWIMAGE}" > ${HOME}/.config/wallpaper/bg_img
else
 # Need to use xsetroot or something.
 true # not implemented.
fi

###END###
