#!/bin/sh

usage()
{
  echo
  echo "Usage:"
  echo "  `basename $0` \$x_resolution \$y_resolution \$file \$wallpaperdir"
  echo
  echo "example:"
  echo "  `basename $0` 1600 1200 /tmp/test.jpg /data/wallpapers"
  exit 1
}

if [ ! $# = 4 ]; then
  usage
fi

XRES="$1"
YRES="$2"
FILE="$3"
WALLPAPERDIR="$4"

if [  ! 0"$XRES" -gt 0 -o \
      ! 0"$YRES" -gt 0 -o \
      ! -d "$WALLPAPERDIR" ]; then
  usage
  exit 1
fi

cd "$WALLPAPERDIR"
randomfile=$(find * \( -iname '*jpg' -or -iname '*jpeg' \) -and -print | \
  perl -e '@a = <STDIN>; print $a[rand $#a];')

# If ratio is nearly similar to the screen ratio, within $MARGIN percent
# then force scaling of the image to get rid of unnecessary narrowblack bars.
PICRATIO=$(identify "$randomfile" | perl -pi -e 'use integer; s#.*\s(\d+)x(\d+)\s.*#{ $1*100/$2; }#ge')
SCREENRATIO=$(($XRES*100/$YRES))
MARGIN=23 #of 100
EXCLAM=''

if [ $PICRATIO -lt $(($SCREENRATIO+$MARGIN)) -a \
  $PICRATIO -gt $(($SCREENRATIO-$MARGIN)) ]; then
  EXCLAM='!'
fi

nice -n 19 convert -size ${XRES}x${YRES} xc:black "$randomfile" \
  -geometry "${XRES}x${YRES}${EXCLAM}" -gravity center -compose src_over -composite \
  -gravity southeast -box black -fill white -draw "text 0,0 \"$randomfile\"" "$FILE.jpg"
# KDE passes a .tmp filename which convert doesn't recognize as output format
mv -f "$FILE.jpg" "$FILE"

echo "Finished"
