#!/usr/bin/env ruby
#
# Copyright (C) 2015 Jan Weil
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

require 'optparse'

options = {}
options[:context_name] = "ctx"

OptionParser.new do |opts|
	opts.banner = "Usage: #{File.basename($0)} [options] <hsm_c_file>..."

	opts.on("-t", "--context-type CONTEXT_TYPE", "Add CONTEXT_TYPE pointer to HSM context") do |type|
		options[:context_type] = type
	end

	opts.on("-n", "--context-name CONTEXT_NAME", "Set the name of the HSM context pointer") do |name|
		options[:context_name] = name
	end
end.parse!

ARGV.each do |file|
	if not File.exist?(file)
		puts "file '#{file}' not found"
		next
	end

	puts "processing #{file}"
	
	states = []
	File.readlines(file).each do |line|
		if line =~ /^MHSM_DEFINE_STATE\(([a-zA-Z0-9_]+),[^)]*\);.*/
			states.push($1)
		end
	end

	open(file, 'a') do |f|
		f.puts "\n"
		for state in states do
			f.puts <<EOC
mhsm_state_t *#{state}_fun(mhsm_hsm_t *hsm, mhsm_event_t event)
{
EOC
			if t = options[:context_type]
				n = options[:context_name]
				f.puts "\t#{t} *#{n} = (#{t}*) mhsm_context(hsm);\n\n"
			end

			f.puts <<EOC
	switch (event.id) {
		case MHSM_EVENT_ENTRY:
			break;
	}

	return &#{state};
}

EOC
		end
	end
end