#!/bin/bash +x

PROC=16
XSETTINGS="-0 -n 1 -P ${PROC} --no-run-if-empty"
PAR="-n 4"
COMPLEVEL="-z4"
OPNGLEVEL="-clobber -o7 -force -fix -quiet -preserve -strip all"

if [ -f work ]; then
	rm work
fi

#build basic regex so it's easy to pass to find
for X;
do
	if [ -f "${X}.zip" ]; then
		continue
	fi
	du -h "${X}"
#	echo "${X}"

	DIR=`mktemp -dup . | sed -E -e 's:^/::'`
	7z x "-o${DIR}" -aou "$X" >/dev/null
	
	D1=`ls "$X" | wc -l`
	
	if [ ! -d "${DIR}" -o ${D1} -eq 0 ]; then
		echo "Error extracting/processing ${X}"
		continue
	fi

	pushd . >/dev/null
	cd "${DIR}"
		#alright, sometimes things are read-only... why? well this still causes issues deleting files. So...
		find -type f ! -writable -print0 | xargs -0 -r chmod +w
		
		#remove dead/pointless files.
		find \( -iname "*.db" -o -iname "*.ini" -o -iname ".github" -o -iname ".DS_store" \) -exec rm {} \;
		find -iname "__MACOSX" -exec rm -r {}/* \; -delete
		
		#remove empty directories, doesn't do much but just in case
		find -type d -empty -delete
		
		#extentions aren't always right.
		/cygdrive/e/x/append_ext.txt
		bash ./work


		#remove read-only from files we might optimize, since advanceComp tools fails on them
		#Windows attrib only takes 1 file at a time... ugg...
		/bin/find -iregex ".*\.\(jpe?g2?\|png\|gif\)" -and ! -writable -exec attrib -r {} \;

		#optimize png images
		#Force two stages for jpeg, since sometimes normal/progressive can have differences, but progressive
		#generally is better.
		/bin/find -iregex ".*\.jpe?g2?" -print0 | xargs ${XSETTINGS} jpegoptim -p --all-progressive --strip-all >/dev/null
		/bin/find -iregex ".*\.jpe?g2?" -print0 | xargs ${XSETTINGS} jpegoptim -p --all-normal --strip-all >/dev/null

		#/bin/find "$@" -iname "*.gif" -print0 | xargs ${XSETTINGS} gifsicle -b --careful&

		/bin/find -iname "*.png" -print0 | xargs ${PAR} ${XSETTINGS} optipng ${OPNGLEVEL} >/dev/null
		/bin/find -iname "*.png" -print0 | xargs ${PAR} ${XSETTINGS} advdef ${COMPLEVEL}  >/dev/null
		
		bash ./unwork
		#add back in all files missing.
		rm work unwork
		
		#get timings from original file?
		7z x -o__touch__ "../${X}" >/dev/null
		find -type f ! -regex '^\./__touch__/.*' -exec touch -r __touch__/{} {} \;
		rm -r __touch__

		#advzip -a0 archive.zip ${DIR}/* >/dev/null
		7z a -mx0 -r "../${DIR}.zip" * >/dev/null
	popd >/dev/null
	#sync

	if [ -f "${DIR}.zip" ]; then
		advzip -z4 "${DIR}.zip" >/dev/null
		mv "${DIR}.zip" "${X}.zip"
		touch -r "${X}" "${X}.zip"
		du -h "${X}.zip"
#		advzip -z3 "${X}.zip" &
		#alright, if the new file is definately smaller, we remove the old one.
		#mini version of mv_larger, but we only need the one way, the other we don't know til later.
		D1=`du "${X}" | sed -e 's/[^0-9].*//'`
		D2=`du "${X}.zip" | sed -e 's/[^0-9].*//'`
		if [ "${D1}" -gt "${D2}" ]; then
			rm "${X}"
		fi

		rm -r "${DIR}"
	else
		echo "${DIR} - ${X}" > "${DIR}/stuck.txt"
	fi
done
