#!/bin/bash
#                       /usr/local/bin/imgs_optimize
# https://crystalfaeries.net/posix/bin/imgs_optimize
# celeste:crystalfaery IMGS_OPTIMIZE 2018-01-05 01:41:33+00:00
# Optimize the imgs in our website at $HOME/crystalfaeries.net/imgs/
# Do a "reset" to start over:
# imgs_optimize -r
# or a normal invocation to continue where we left off...:
# imgs_optimize

help=10	# line#-1

#	CONFIGURATION and ARGUMENTS
dirroot="$HOME/crystalfaeries.net/imgs/"	# root of directories to optimize
cd -P ${dirroot}	||	alert "$0 unable to cd into ${dirroot}"

dirlist="${dirroot}/.optimize.txt"	# list of directories to optimize within imgs root
if [ -s ${dirlist} ]
then	# we have an existing list of directories to optimize
	if [ $# -eq 0 ]
	then	# continue with existing list
		touch ${dirlist}	# kilroy was here
	else	# uh oh, really reset the list?
		if [ "${1}" == "-r" ]
		then	# we have an argument requesting reset
			lsdir | tac | grep -v '^\.' | grep -v .html | grep -v .css | sed 's/\/$//' > ${dirlist}
		else	# we have a NON-reset argument
			if [ "${1}" == "-v" ]
			then	# we have an argument requesting version
				tail -n +4 $0 | head -n 1 1>&2	# output version information
				exit	0	# it is normal to exit after version.
			else	# we have a help argument
				head -n ${help} $0 1>&2	# output helpful information
				exit	0	# it is normal to exit after helping.
			fi
		fi
	fi
else	# we must generate a list of directories to optimize
	lsdir | tac | grep -v '^\.' | grep -v .html | grep -v .css | sed 's/\/$//' > ${dirlist}
fi

while [ -s ${dirlist} ]
do
	dir=$(head -n 1		${dirlist})	# next directory to optimize
	echo	"$(basename $0): optimizing	${dir}"	1>&2	# progress to errout
	optimizeimg				${dir}	|| exit	$?	#	error optimizing
	echo	"$(basename $0): optimized	${dir}"	1>&2	# progress to errout
	grep -v	"${dir}"	${dirlist}	\
	>	/tmp/.$$.txt			||	exit	254	# remove just completed dir from todo list
	mv	/tmp/.$$.txt	${dirlist}	||	exit	255	# error updating dirlist
done

exit	$?
