#!/usr/bin/env ruby

def command(c)
	puts c
	unless system(c)
		puts "Error while converting data"
		exit(1)
	end
end

# read texture options file
texture_options = Hash.new {|h, v| h['default']}
texture_options['default'] = 'INDEX8 MIPMAP DITHER' # default default
File.open('graphics/textures/options.txt') do |f|
	until f.eof?
		name, opt = f.gets.split(':', 2)
		texture_options[name.strip] = opt.strip
	end
end

# read status file
$status = {}
Status = Struct.new(:time, :options)
begin
	File.open('graphics/status.txt') do |f|
		until f.eof?
			name, tail = f.gets.split(':', 2)
			time, opt = tail.split(' ', 2)
			$status[name.strip] = Status.new(time.to_i, opt.strip)
		end
	end
rescue Errno::ENOENT
end

def convertDir(dir)
	Dir.open(dir) do |d|
		d.each do |file|
			base, ext = file.split(/\.(?=[^.]*\Z)/)
			com, options = yield file, base, ext
			next unless com
			next if $status[file] &&
				$status[file].time > File.mtime(dir + '/' + file).to_i &&
				$status[file].options == options
			$status[file] = Status.new(Time.now.to_i, options)
			command(com + ' ' + options)
		end
	end
end

# go through all textures and see which need to be reconverted
convertDir('graphics/textures') do |file, base, ext|
	if ext && ext != 'txt'
		["texconv/texconv_odebug graphics/textures/%s data/%s.tex" % [file, base],
			texture_options[base]]
	else
		nil
	end
end

# read .i files
defines = {}
['shared/vucamera.i', 'intmdloader/intmdvu.i'].each do |n|
	File.open(n) do |f|
		f.each do |line|
			m = /(\w+)\s+\.equ\s+(.*)/.match(line)
			if m
				name = m[1]
				value = m[2]
				value.gsub!(/H'/, '0x')
				defines.each do |k, v|
					value.gsub!(Regexp.new(Regexp.escape(k) + '(?!\w)'), v.to_s)
				end
				defines[name] = eval(value)
			end
			
		end
	end
end

convertDir('graphics/static') do |file, base, ext|
	if ext == 'xsi'
		["xsiconv/main_odebug graphics/static/%s data/" % file, defines['INT_MAXVERTICES'].to_s]
	else
		nil
	end
end

# write back status file
File.open('graphics/status.txt', 'w') do |f|
	$status.each do |k, v|
		f.printf("%s: %i %s\n", k, v.time, v.options)
	end
end
