#! /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,sys
from waflib import Task,TaskGen,Logs
R_COMMANDS=['RTerm','R','r']
def configure(ctx):
	ctx.find_program(R_COMMANDS,var='RCMD',errmsg="""\n
No R executable found!\n\n
If R is needed:\n
	1) Check the settings of your system path.
	2) Note we are looking for R executables called: %s
	   If yours has a different name, please report to hmgaudecker [at] gmail\n
Else:\n
	Do not load the 'run_r_script' tool in the main wscript.\n\n"""%R_COMMANDS)
	ctx.env.RFLAGS='CMD BATCH --slave'
@Task.update_outputs
class run_r_script_base(Task.Task):
	run_str='"${RCMD}" ${RFLAGS} "${SRC[0].abspath()}" "${LOGFILEPATH}"'
	shell=True
class run_r_script(run_r_script_base):
	def run(self):
		ret=run_r_script_base.run(self)
		logfile=self.env.LOGFILEPATH
		if ret:
			mode='r'
			if sys.version_info.major>=3:
				mode='rb'
			with open(logfile,mode=mode)as f:
				tail=f.readlines()[-10:]
			Logs.error("""Running R on %s returned the error %r\n\nCheck the log file %s, last 10 lines\n\n%s\n\n\n"""%(self.inputs[0].nice_path(),ret,logfile,'\n'.join(tail)))
		else:
			os.remove(logfile)
		return ret
@TaskGen.feature('run_r_script')
@TaskGen.before_method('process_source')
def apply_run_r_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_r_script',src=src_node,tgt=tgt_nodes)
	tsk.env.LOGFILEPATH=os.path.join(tg.bld.bldnode.abspath(),'%s_%d.log'%(os.path.splitext(src_node.name)[0],tg.idx))
	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=[]
