 cat /usr/local/bin/directory-thumbnailer
#!/bin/bash
IFS=$'\n\t'

# not enough args
if [ $# -lt 3 ]; then
	exit 1
fi

# extract args for execution
size="$1"
in="$2"
out="$3"

# pre-flight check that $in is not a home user folder (we don't want to modify those)
if [ "$HOME" = "$(dirname $in)" ]; then
	exit 0
fi

# fine image files that we can extract
# @todo: add support for video files
files=()
for f in "$(find "$in" -maxdepth 1 -type f -exec file {} \; | grep -o -P '^.+: \w+ image' | sort -n | head -4 | cut -d':' -f1)"; do
	files+=($f)
done
[ ${#files[*]} -gt 0 ] || exit 1

# extract theme or use gnome as default
config="${XDG_CONFIG_HOME:-$HOME/.config}/gtk-3.0/settings.ini"
icon_theme="$(grep 'gtk-icon-theme-name' "$config" | sed 's/.*\s*=\s*//')"
icon_theme="${icon_theme:-gnome}"

# @todo: add behavior to try to get appropriate size first, else fallback to assumed largest/last
folder_icon=$(find "/usr/share/icons/$icon_theme" -name "folder.*" | sort -d | tail -1)

# check if folder icon exists
# @todo: consider using known gnome folder icon as fallback
if [ ! -f "$folder_icon" ]; then
	exit 1
fi

# generate the thumbnail
convert -background none "$folder_icon" -resize $size <(montage -geometry "$(($size * 60 / 200))x$(($size * 60 / 300))+2+2" -alpha on -background none -tile 2 ${files[*]} png:-) -gravity center -composite "$out" 2>/dev/null
