#!/usr/bin/ruby
# Original script
# Copyright (C) 2004 by Crossbow/Miyo <miyo@iki.fi>
# Some features and Ruby-fication
# Copyright (C) 2005 by Isaac Clerencia <isaac@warp.es>
# Part of the Battle for Wesnoth Project http://www.wesnoth.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY.
#
# See the COPYING file for more details.
# 
# Scipt to strip ICC profiles from all png images and to compress them
# afterwards via optipng
# 
# Requirements: ruby, imagemagick, optipng
# HowToUse: start the script from the wesnoth maindir
# 'svn ci' to commit the stuff
# enter a commit message
# enjoy ICC-profile clean and size-optimised png images
#

require 'md5'

def sha1sum(file)
	MD5.new(open(file).read).hexdigest
end

checkOld = true

totalSavedBytes = 0
totalSavedFiles = 0

files = (`find -iname "*.png"`).split("\n")

files.each { | file| 
	file = file[2,file.length]
	puts "\n* processing #{file}\n"

#	old = "/home/isaac/devel/wesnoth/last/#{file}";
#	if checkOld and File.exists?(old) and sha1sum(file) == sha1sum(old)
#		puts "  * no change since last release\n";
#		next;
#	end
	output = `nice -n 19 convert -strip "#{file}" "#{file}.stripped.png"`;
#	output = `nice -n 19 pngcrush -brute -q "#{file}.stripped.png" "#{file}.new.png"`;
	output = `nice -n 19 optipng -q -o5 -nb -nc -np "#{file}.stripped.png" -out "#{file}.new.png"`;
	output = `rm "#{file}.stripped.png"`
	File.exists?("#{file}.new.png") or next;
	oldSize = File.size(file)
	newSize = File.size("#{file}.new.png")
	if newSize < oldSize
		savedBytes = oldSize - newSize;
		totalSavedBytes = totalSavedBytes + savedBytes
		totalSavedFiles = totalSavedFiles.succ
		output = `mv "#{file}.new.png" -v "#{file}"`
		puts ",\nsaved: #{savedBytes} bytes, total saved: #{totalSavedBytes/1024} KiB"
	else
		File.unlink("#{file}.new.png");
	end
}

puts "\ntotal saved: #{totalSavedBytes/1024} KiB, #{totalSavedFiles} files\n";
