#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file

import os,re,sys
from waflib import Task,TaskGen,Logs
if sys.platform=='darwin':
	STATA_COMMANDS=['Stata64MP','StataMP','Stata64SE','StataSE','Stata64','Stata']
	STATAFLAGS='-e -q do'
	STATAENCODING='MacRoman'
elif sys.platform.startswith('linux'):
	STATA_COMMANDS=['stata-mp','stata-se','stata']
	STATAFLAGS='-b -q do'
	STATAENCODING='Latin-1'
elif sys.platform.lower().startswith('win'):
	STATA_COMMANDS=['StataMP-64','StataMP-ia','StataMP','StataSE-64','StataSE-ia','StataSE','Stata-64','Stata-ia','Stata.e','WMPSTATA','WSESTATA','WSTATA']
	STATAFLAGS='/e do'
	STATAENCODING='Latin-1'
else:
	raise Exception("Unknown sys.platform: %s "%sys.platform)
def configure(ctx):
	ctx.find_program(STATA_COMMANDS,var='STATACMD',errmsg="""\n
No Stata executable found!\n\n
If Stata is needed:\n
	1) Check the settings of your system path.
	2) Note we are looking for Stata executables called: %s
	   If yours has a different name, please report to hmgaudecker [at] gmail\n
Else:\n
	Do not load the 'run_do_script' tool in the main wscript.\n\n"""%STATA_COMMANDS)
	ctx.env.STATAFLAGS=STATAFLAGS
	ctx.env.STATAENCODING=STATAENCODING
@Task.update_outputs
class run_do_script_base(Task.Task):
	run_str='"${STATACMD}" ${STATAFLAGS} "${SRC[0].abspath()}" "${DOFILETRUNK}"'
	shell=True
class run_do_script(run_do_script_base):
	def run(self):
		run_do_script_base.run(self)
		ret,log_tail=self.check_erase_log_file()
		if ret:
			Logs.error("""Running Stata on %s failed with code %r.\n\nCheck the log file %s, last 10 lines\n\n%s\n\n\n"""%(self.inputs[0].nice_path(),ret,self.env.LOGFILEPATH,log_tail))
		return ret
	def check_erase_log_file(self):
		if sys.version_info.major>=3:
			kwargs={'file':self.env.LOGFILEPATH,'mode':'r','encoding':self.env.STATAENCODING}
		else:
			kwargs={'name':self.env.LOGFILEPATH,'mode':'r'}
		with open(**kwargs)as log:
			log_tail=log.readlines()[-10:]
			for line in log_tail:
				error_found=re.match("r\(([0-9]+)\)",line)
				if error_found:
					return error_found.group(1),''.join(log_tail)
				else:
					pass
		os.remove(self.env.LOGFILEPATH)
		return None,None
@TaskGen.feature('run_do_script')
@TaskGen.before_method('process_source')
def apply_run_do_script(tg):
	src_node=tg.path.find_resource(tg.source)
	tgt_nodes=[tg.path.find_or_declare(t)for t in tg.to_list(tg.target)]
	tsk=tg.create_task('run_do_script',src=src_node,tgt=tgt_nodes)
	tsk.env.DOFILETRUNK=os.path.splitext(src_node.name)[0]
	tsk.env.LOGFILEPATH=os.path.join(tg.bld.bldnode.abspath(),'%s.log'%(tsk.env.DOFILETRUNK))
	for x in tg.to_list(getattr(tg,'deps',[])):
		node=tg.path.find_resource(x)
		if not node:
			tg.bld.fatal('Could not find dependency %r for running %r'%(x,src_node.nice_path()))
		tsk.dep_nodes.append(node)
	Logs.debug('deps: found dependencies %r for running %r'%(tsk.dep_nodes,src_node.nice_path()))
	tg.source=[]
