#! /usr/bin/env python
# encoding: utf-8

from waflib import Task, Options, Logs
import shutil, os, os.path 

def options(opt):
    pass

def configure(conf):
    LD = conf.find_program('ld')

def need_rebuild(bld, sources):
    need_run = False
    for f in sources:
        if not os.path.isfile('%s/src/LV2/xputty/resources/%s.o' % (bld.out_dir, os.path.splitext(f.name)[0])):
            need_run = True
    return need_run

def img2h(task):
    src = " ".join(["'%s_png'" % os.path.splitext(v.name)[0] for v in task.inputs[0:]])
    cmd = ("rm -f ../src/LV2/xputty/resources/xresources.h && \
    for f in %s; do echo 'EXTLD('$f')' >> ../src/LV2/xputty/resources/xresources.h; done" % src)
    # win32: dont use cmd.exe as shell
    if task.env['OS'] == 'win32':
        cmd = 'bash -c "%s"' % cmd
    ret = task.exec_command(cmd, shell=True)
    return ret

def copyimg(task):
    task.no_errcheck_out = True
    img2h(task)
    before = ['xcairo']
    src = " ".join(["'%s'" % v.bldpath() for v in task.inputs[0:]])
    cmd = (" cp %s src/LV2/xputty/resources/ " % src )
    ret = task.exec_command(cmd, shell=True)
    return ret

def img2obj(task):
    env = task.env
    task.no_errcheck_out = True
    copyimg(task)
    before = ['xcairo']
    src = " ".join(["'%s'" % os.path.splitext(v.name)[0] for v in task.inputs[0:]])
    # win32: fix dir-separator, remove non-existing flag
    ld_cmd = env.LD[0]
    noexecstack = task.env['OS_RESOURCES_LDFLAGS']
    if task.env['OS'] == 'win32':
        ld_cmd = ld_cmd.replace('\\','/')
    cmd = ("cd src/LV2/xputty/resources/ \
    && for f in %s; do\
     %s -r -b binary %s ${f}.png -o  ${f}.o; \
     done " % (src, ld_cmd, noexecstack) )
    # win32: dont use cmd.exe as shell
    if task.env['OS'] == 'win32':
        cmd = 'bash -c "%s"' % cmd
   # Logs.debug("runner: system command -> %s" % cmd)
    ret = task.exec_command(cmd, shell=True)
    return ret

def build(bld):
    if not (bld.env.LV2GUI):
        return None
    resources = bld.path.ant_glob('*.png')

    if not (need_rebuild(bld, resources)):
        return None

    targ = (''.join([' %s.o'% os.path.splitext(v.name)[0] for v in resources]))
    re_sources = targ.split()

    res = bld(name = 'resources',
        rule = img2obj,
        source = resources,
        target = re_sources
        )
    res.install_path = None
    bld.add_group()
