#!/usr/bin/env python
#
#	Generate occam-pi .module files from XML descriptions
#	Copyright (C) 2007 University of Kent
#
#	This program is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program; if not, write to the Free Software
#	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import sys, xml.dom.minidom, os

def die(*s):
	print >>sys.stderr, "kmakemodule: " + "".join(map(str, s))
	sys.exit(1)

def handle(f, group, tag, format):
	els = group.getElementsByTagName(tag)
	for el in els:
		if el.firstChild.nodeType != el.TEXT_NODE:
			die("expected text node in ", tag)
		f.write(format % el.firstChild.data)
	if els != []:
		f.write("\n")

def generate(ifn):
	ifnbase = os.path.basename(ifn)
	try:
		module = xml.dom.minidom.parse(ifn).documentElement
	except:
		die("unable to parse input file ", ifn)

	name = module.getAttribute("name").strip()
	ofn = name + ".module"
	f = open(ofn, "w")
	f.write('-- Include file for "%s" module\n' % name)
	f.write('-- Automatically generated by kmakemodule from %s\n' % ifnbase)
	f.write("\n")

	guard = ofn.replace("_", ".").upper()
	f.write("#IF NOT (DEFINED (%s))\n" % guard)
	f.write("#DEFINE %s\n" % guard)
	f.write("\n")

	handle(f, module, "needsModule", '#INCLUDE "%s.module"\n')
	handle(f, module, "include", '#INCLUDE "%s"\n')
	handle(f, module, "use", '#USE "%s"\n')
	handle(f, module, "library", '#PRAGMA COMMENT ".USELIB %s"\n')

	f.write("#ENDIF\n")
	f.close()

if __name__ == "__main__":
	for filename in sys.argv[1:]:
		generate(filename)

