#!/usr/bin/ruby
require 'find'

Find.find( ARGV[0] ) do | file |
  if file.match( '\.gif$' )
    command = sprintf( 'gifsicle --batch -O2 %s', file )
    puts command
    system( command )
  end
  if file.match( '\.jpe?g$' )
    command = sprintf( 'jpegtran -copy none -optimize -outfile %s %s', file, file )
    puts command
    system( command )
  end
  if file.match( '\.png$' )
    new_file = "#{file}-crushed"
    command = sprintf( 'pngcrush -q -rem alla -brute -reduce %s %s', file, new_file )
    puts command
    system( command )
    if File.exists?( new_file )
      if File.size( new_file) < File.size( file )
        command = "mv #{new_file} #{file}"
      else
        command = "rm #{new_file}"
      end
      puts command
      system( command )
    end
  end
end
