#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Desc:    This file is part of the eCromedos document preparation system
# Date:    2006/03/09
# Author:  Tobias Koch (tkoch@ecromedos.net)
# License: GNU General Public License, version 2
# URL:     http://www.ecromedos.net
#

# std includes
import os, sys, libxml2

# eCromedos includes
from error import ECMDSError, ECMDSPluginError
from ecmdsproc import ECMDSProc

# exit values
ECMDS_ERR_INVOCATION = 1
ECMDS_ERR_PROCESSING = 2

# version number
VERSION = "1.0.1"

def printVersion():
	'''Display version information.'''

	print "eCromedos document processor version %s               " % (VERSION,)
	print "Copyright (C) 2005-2006 Tobias Koch (tkoch@ecromedos.net)"
#end function


def printUsage():
	'''Display usage information.'''

	printVersion()

	print "                                                      "
	print "Usage: ecromedos [OPTIONS] source                     "
	print "                                                      "
	print "Options:                                              "
	print "                                                      "
	print " --help         Display this information              "
	print " --novalid      Do not try to validate document       "
	print "                                                      "
	print " -f format      Generate XHTML (default) or LaTeX     "
	print " -s directory   Use stylesheets from given directory  "
	print " -c file        Use alternative configuration file    "
	print " -v             Print version information and exit    "
#end function


def parseCmdLine():
	'''Parse and extract arguments of command line options.'''

	options = {}

	def getArg(i, opt):
		try:
			return sys.argv[i]
		except IndexError:
			msg = "Option '%s' is missing an argument" % (opt,)
			raise ECMDSError(msg)
		#end try
	#end inline function

	i = 1
	while i < len(sys.argv):
		arg = sys.argv[i]
		if arg[0] == '-':
			i += 1
			if arg == "--help":
				printUsage()
				sys.exit(0)
			elif arg == "-v":
				printVersion()
				sys.exit(0)
			elif arg == "-f":
				options["target_format"] = getArg(i, arg).lower()
			elif arg == "-s":
				options["style_dir"] = getArg(i, arg)
			elif arg == "-c":
				options["config_file"] = getArg(i, arg)
			elif arg == "--novalid":
				options["do_validate"] = "no"
				i -= 1
			else:
				msg = "Unrecognized option '%s'" % (arg,)
				raise ECMDSError(msg)
			#end if
		else: break
		i += 1
	#end while
	
	return options, sys.argv[i:]
#end function


if __name__ == "__main__":

	# INIT XML-CATALOG
	libxml2.initializeCatalog()

	# SETUP
	try:
		# parse command line
		options, files = parseCmdLine()
		if len(files) < 1:
			msg = "You did not specify an input file"
			raise ECMDSError(msg)
		#end if
	except ECMDSError, e:
		sys.stderr.write(e.msg() + "\n")
		sys.stderr.write("Type 'ecromedos --help' for more information\n")
		sys.exit(ECMDS_ERR_INVOCATION)
	#end try

	# RUN
	try:
		proc = ECMDSProc()
		proc.process(files[0], options)
	except ECMDSPluginError, e:
		msg = "Plugin '%s' caused an error:\n %s" % (e.pluginName(), e.msg())
		sys.stderr.write(msg + "\n")
		sys.exit(ECMDS_ERR_PROCESSING)
	except ECMDSError, e:
		sys.stderr.write(e.msg() + "\n")
		sys.exit(ECMDS_ERR_PROCESSING)
	#end try

#end __main__
