#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Command to build the documentation"""
__docformat__ = "restructuredtext"

import os
import sys


#{ Initialization

def prepare_project_package():
	"""Assure we are able to import the root package. If this is not the case, 
	resort to manually including the required code to set everything up"""
	ospd = os.path.dirname
	mrvpath = os.path.join(ospd(ospd(os.path.realpath(os.path.abspath(__file__)))),'mrv', 'bin', 'mrv')
	globals()['__name__'] = "prevent execution of main"
	globals()['__file__'] = mrvpath
	
	try:
		execfile(mrvpath, globals())
	except Exception, e:
		raise EnvironmentError("Could not execute mrv at %r with error %s" % (mrvpath, e))
	# END exception handling
	
	prepare_project_syspath()


def makedoc_main(args):
	"""Parse args, initialize a builder, and run it"""
	prepare_project_package()
	import mrv
	import mrv.info
	
	# import docgenerator
	var = "docgen_class_path"
	gen_path = getattr(mrv.pinfo, var, getattr(mrv.info, var))
	tokens = gen_path.split('.')
	try:
		genmod = __import__('.'.join(tokens[:-1]), globals(), locals(), [tokens[-1]])
	except ImportError:
		raise ImportError("Docgenerator class path %r did not lead to a valid module" % gen_path)
	#END handle exceptions
	
	# DOC GENERATION
	################
	if not hasattr(genmod, tokens[-1]):
		raise EnvironmentError("DocGenerator at path %r did not exist" % gen_path)
	#END verify class exists

	# assume the best, just fail if something is wrong with the type - its up
	# to the programmer to fix it, and he should get a full stack-trace
	getattr(genmod, tokens[-1]).makedoc(args)

#} END initialization


# run the script 
if __name__ == "__main__":
	makedoc_main(sys.argv[1:])
