#!/bin/bash

case "$1" in
	-f)
		force=true
		shift
	;;
	*)
	;;
esac

if [ $# = 0 ]; then
  str="*"
else
  str=$@
fi


exiftool=$( type -p exiftool )
if [ ! -x "$exiftool" ]; then
	echo exiftool not found. Fatal.
	exit 5
fi

convert=$( type -p convert )
if [ ! -x "$convert"  ]; then
	echo convert not found. Fatal.
	exit 6
fi

for i in $( find $str -type f -name '*.jpg' | sort ) ; do 

    if [ "$force" = true ]; then
	hastn=no
    else
	if ! ( $exiftool "$i" | grep 'Thumbnail Length' > /dev/null ) ; then
		hastn=no
	else
		hastn=yes
		echo "$i has tn."
	fi
    fi

    if [ "$hastn" = no ]; then
	# create tn image:
	$convert -quality 50 -resize 128x128 "$i" Tn.jpg
	# add Tn.jpg to the image
	echo -n "$i "
	$exiftool -P '-ThumbnailImage<=Tn.jpg' "$i"
	if [ $? = "0" ]; then
		rm -f Tn.jpg "$i"_original
	else
		echo not removed: "$i"_original
		rm -f Tn.jpg
	fi
    fi

done
