#!/bin/bash
#                      /usr/local/bin/optimizeimg
# http://crystalfaeries.net/posix/bin/optimizeimg
# celeste:crystalfaery 2016-11-08 22:03:33+00:00
# Optimize images (after tidying their names)
# any argument is a directory to process recursively
#                      otherwise process the current directory

if		[ "X$1" = "X" ]
then				# if no arguments, work in current directory
		name_tidy -r	.	# recursively
		if [ -x `which parallel` ]
		then
			parallel -u 'echo {}; jpegtran -optimize -progressive -perfect -copy all -outfile {}.tran {} && mv {}.tran {}' ::: *.jpg *.jpeg
		else
			for f in *.jpg *.jpeg
			do
				jpegtran -optimize -progressive -perfect -copy all $f > $f.jpg
			done
		fi
		find	.	   -iname '*.JPG' -o -iname '*.JPEG'								-print0 | xargs -0 jpegoptim
		find	.	\( -iname '*.PNG' -o -iname '*.BMP' -o -iname '*.GIF' -o -iname '*.PNM' -o -iname '*.TIFF' \)	-print0 | xargs -0 optipng -nc -nb -o7 -fix -snip
		dudir >	.du.txt	# update disk usage report
		touch	.	# kilroy was here
else				# if any arguments...
	until	[ "X$1" = "X" ]
	do			# work in each directory given as an argument
	    pushd "$1" || break	# work in specified directory else error exit on bad directory
	    shift		# we used the argument to do what it was needed for, so consume it
		name_tidy -r	.	# recursively
		if [ -x `which parallel` ]
		then
			parallel -u 'echo {}; jpegtran -optimize -progressive -perfect -copy all -outfile {}.tran {} && mv {}.tran {}' ::: *.JPG *.jpg *.jpeg *.JPEG
		else
			for f in *.jpg *.jpeg
			do
				jpegtran -optimize -progressive -perfect -copy all $f > $f.jpg
			done
		fi
		find	.	   -iname '*.JPG' -o -iname '*.JPEG'								-print0 | xargs -0 jpegoptim
		find	.	\( -iname '*.PNG' -o -iname '*.BMP' -o -iname '*.GIF' -o -iname '*.PNM' -o -iname '*.TIFF' \)	-print0 | xargs -0 optipng -nc -nb -o7 -fix -snip
		dudir >	.du.txt	# update disk usage report
		touch	.	# kilroy was here
	    popd			# return to starting directory so arguments can be relative paths
	done
fi
exit	0	# we are not yet really handling errors



syntax highlighted by Code2HTML, v. 0.9.1