#!/bin/bash
#
# Identifies and fixes all png's that contain transparent,colored pixels (which can be problematic) and creates a 7z archive with the updated cursors. 
# See http://trac.wildfiregames.com/ticket/2823
#
# Requires 'idenify' and 'convert' of the image magick commandline tool http://www.imagemagick.org/script/identify.php
# Available on Debian and Ubuntu via 'sudo apt-get install imagemagick'.

# Place the script into 0ad's trunk directory and execute without arguments.

# pngs in the following directories will be updated:
subdir1=binaries/data/mods/mod/art/textures/cursors/;
subdir2=binaries/data/mods/public/art/textures/cursors/;

# ------------------------------------------------------------------------------------------------------------
# Now tell bash to only split the input on newlines:
# see https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names
OIFS="$IFS"
IFS=$'\n'

filesFixed="";

# check all png's
for filename in $(find $subdir1 $subdir2 -name *.png); do

	if [[ "$filename" == *_old.png ]]; then
		continue;
	fi

	# first grep for histogram lines, like
	#        26: (  2,  1,  1,  0) #02010100 srgba(2,1,1,0)
	# then extract text of each line between the sixth = last comma and the first parenthesis after that
	for alpha in `identify -verbose "$filename" | grep 'srgba(' | cut -d ',' -f 7 | cut -d ')' -f 1`; do

		if [ "$alpha" == "0" ]
		then
			echo "Fixing $filename"
			mv "$filename" "${filename}_old.png";

			# fix taken from http://www.imagemagick.org/discourse-server/viewtopic.php?t=13746
			convert  "${filename}_old.png" -fx 'a==0 ? 0 : u' "$filename";

			filesFixed="$filesFixed \"$filename\""
			continue 2;
		fi

	done

	#echo "$filename does not need to be fixed";
done

IFS="$OIFS"
# ------------------------------------------------------------------------------------------------------------

# create a 7zip archive
if [ "$filesFixed" != "" ]; then

	# delete old file if exists
	if [ -e "cursors_fixed.7z" ]; then
		rm "cursors_fixed.7z";
	fi

	eval "7z a -mx=9 cursors_fixed.7z $filesFixed"
fi
