#!/usr/bin/env ruby

$release_dir = "release"

def basename(file)
	idx = file.rindex(".")
	if idx then
		file[0..(idx - 10)] #8 digits + 1 underscore + 1 dot
	else
		file
	end
end

def diff(f1, f2)
	case f1
	when /\.jar\'$/
		d1 = f1[0..-6] + "'"
		d2 = f2[0..-6] + "'"
		`unzip #{f1} -d #{d1}`
		`unzip #{f2} -d #{d2}`
		`diff -r #{d1} #{d2}`
		result = $?
		`rm -rf #{d1}`
		`rm -rf #{d2}`
		return result != 0
	else
		`diff #{f1} #{f2}`
		return $? != 0
	end
end

def cull!(files)
	files.sort!.reverse! #want newer dates first
	(files.length - 1).times do |i|
		f1 = "'#{$release_dir}/#{files[i]}'"
		f2 = "'#{$release_dir}/#{files[i+1]}'"
		puts "Comparing: #{files[i]} #{files[i+1]}"
		if !diff(f1, f2) then
			puts "  Deleting #{files[i]}"
			`rm #{f1}`
		else
			puts "  No duplication"
		end
	end
end

Dir.open($release_dir) do |dir|
	files = dir.entries.delete_if {|f| f =~ /^\./ }
	map = {}
	files.each do |file|
		bname = basename(file)
		if !map[bname] then
			map[bname] = []
		end
		map[bname] << file
	end
	map.each_value do |same_basename|
		cull!(same_basename)
	end
end