import os

from task \
    import \
        Task
from task_manager \
    import \
        extension
from utils \
    import \
        find_deps, ensure_dir
from compiled_fun \
    import \
        compile_fun

ccompile, cc_vars = compile_fun("cc", "${CC} ${CFLAGS} ${INCPATH} -o ${TGT[0]} -c ${SRC}", False)

cshlink, cshlink_vars = compile_fun("cshlib", "${SHLINK} ${SHLINKFLAGS} -o ${TGT[0]} ${SRC}", False)

@extension('.c')
def c_hook(self, node):
    tasks = ccompile_task(self, node)
    self.object_tasks.extend(tasks)
    return tasks

def ccompile_task(self, node):
    base = os.path.splitext(node)[0]
    # XXX: hack to avoid creating build/build/... when source is
    # generated. Dealing with this most likely requires a node concept
    if not os.path.commonprefix([self.env["BLDDIR"], base]):
        target = os.path.join(self.env["BLDDIR"], base + ".o")
    else:
        target = base + ".o"
    ensure_dir(target)
    task = Task("cc", inputs=node, outputs=target)
    task.env_vars = cc_vars
    #print find_deps("foo.c", ["."])
    #task.scan = lambda : find_deps(node, ["."])
    #task.deps.extend(task.scan())
    task.env = self.env
    task.func = ccompile
    return [task]

def link_task(self, name):
    objects = [tsk.outputs[0] for tsk in self.object_tasks]
    target = os.path.join(self.env["BLDDIR"], name + ".so")
    ensure_dir(target)
    task = Task("cc_link", inputs=objects, outputs=target)
    task.func = cshlink
    task.env_vars = cshlink_vars
    return [task]

@@ -373,16 +373,42 @@
 NKFLAGS%7D
+ $%7BAPP_LIBDIR%7D $%7BAPP_LIBS%7D
  -o $%7BTG
@@ -1442,32 +1442,56 @@
 outputs=target)%0A
+    task.env = self.env%0A
     task.func = 
@@ -1533,24 +1533,507 @@
 _vars%0A    return %5Btask%5D%0A
+%0Adef apply_libs(task_gen):%0A    libs = task_gen.env%5B%22LIBS%22%5D%0A    task_gen.env%5B%22APP_LIBS%22%5D = %5B%0A            task_gen.env%5B%22LIBS_FMT%22%5D %25 lib for lib in libs%5D%0A%0Adef apply_libdir(task_gen):%0A    libdir = task_gen.env%5B%22LIBDIR%22%5D%0A    implicit_paths = set(%5B%0A        os.path.join(task_gen.env%5B%22BLDDIR%22%5D, os.path.dirname(s))%0A        for s in task_gen.sources%5D)%0A    libdir = list(implicit_paths) + libdir%0A    task_gen.env%5B%22APP_LIBDIR%22%5D = %5B%0A            task_gen.env%5B%22LIBDIR_FMT%22%5D %25 d for d in libdir%5D%0A

add LIBDIR and LIBS handling in ctasks.