#!/bin/bash
#                      /usr/local/bin/optimizeimg
# http://crystalfaeries.net/posix/bin/optimizeimg
# celeste:crystalfaery 2020-08-29 11:47:10+00:00
# Optimize images (after tidying their names)
# any argument is a directory to process recursively
#                      otherwise process the current directory
# originally written to use optipng -o7 max compression,
# we have found in practical use that is impractical on laptop.

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
# optipng cognizes .PNG BMP GIF TIFF PNM PBM PGM PPM
		find	.	\( -iname '*.PNG' -o -iname '*.BMP' -o -iname '*.GIF' -o -iname '*.PNM' -o -iname '*.TIFF' \)	-print0 | xargs -0 optipng -nc -nb -o6 -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 -o6 -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	$?	#	end of functional code

# What may we learn from these?

# http://www.commandlinefu.com/commands/view/24050/find-and-reduce-8x-parallel-the-size-of-jpg-images-without-loosing-quality-via-jpegoptim
find /var/www/htdocs/*/docroot/ -type f -name '*.[jJ][pP][gG]' -print0 | xargs -n 1 -P 8 -0 jpegoptim --strip-all --preserve --preserve-perms --quiet

# https://www.commandlinefu.com/commands/view/24049/find-and-reduce-8x-parallel-the-size-of-png-images-without-loosing-quality-via-optipng
find /var/www/ -type f -name '*.[pP][nN][gG]' -print0 | xargs -L 1 -n 1 -P 8 -0 optipng -preserve -quiet -o6 -f4 -strip all

