#!/bin/bash
set -e

month=`date +%B | dd conv=ucase status=none`

[ $# -eq 2 -o $# -eq 3 ] || {
  echo "wpren shuffler plugin  <https://aleteoryx.me/>"
  echo "Usage: $(basename $0) SRC-DIR DST-DIR [IDENTIFIER]" 1>&2
  echo "" 1>&2
  echo "If IDENTIFIER is missing, it will default to the current month, uppercased. Right now, that's '$month'." | fold -s 1>&2
  echo "" 1>&2
  echo "See <https://aleteoryx.me/downloads2/utils/wpren/plugins/shuffler/> for full documentation and usage notes." | fold -s 1>&2
  exit -1
}

src="$1"
dst="$2"
ident="${3:-month}"

[ -d $src ] || {
  echo "$src: Not a directory." 1>&2
  exit -2
}
[ -d $dst ] || {
  echo "$dst: Not a directory." 1>&2
  exit -3
}

images=("$src"/*"$ident"*.png)
set -a images
[ $images == "$src/*$ident*.png" ] && {
  rm -f "$dst/index.png"
  echo "No source files, deleting index.png" 1>&2
  exit 0
}

wallpaper=${images[$((RANDOM % ${#images[@]}))]}
cp $wallpaper "$dst/index.png"
