
def configure(ctx):
    from os.path import join

    lds_path = join(ctx.env.ARCH_D, "boot.ld")

    ctx.env.append_value('DEFINES_EFI', [
        'KERNEL_FILENAME=L"{}"'.format(ctx.env.KERNEL_FILENAME),
        'GNU_EFI_USE_MS_ABI',
        'HAVE_USE_MS_ABI',
        'EFI_DEBUG=0',
        'EFI_DEBUG_CLEAR_MEMORY=0',
    ])
    ctx.env.append_value('CFLAGS_EFI', ['-fPIC', '-fshort-wchar'])
    ctx.env.append_value('LINKFLAGS_EFI', [
        '-shared',
        '-T', lds_path,
    ])
    ctx.env.append_value('SECTIONS_EFI', [
    ])

def build(bld):
    sources = bld.path.ant_glob("**/*.c")
    sources += bld.path.ant_glob("**/*.s")

    bld.program(
        source      = sources,
        target      = "boot.elf",
        use         = 'EFI',
    )

    from waflib.Task import Task
    class make_efi(Task):
        color = 'YELLOW'
        def keyword(self):
            return "Creating"
        def __str__(self):
            node = self.outputs[0]
            return node.path_from(node.ctx.launch_node())
        def run(self):
            from subprocess import check_call as call

            args = self.env.objcopy
            sections = [".text", ".sdata", ".data", ".dynamic",
                        ".dynsym", ".rel", ".rela", ".reloc"]
            for s in sections: args.extend(['-j', s])
            args.append('--target=efi-app-' + self.env.POPCORN_ARCH)
            args.append(self.inputs[0].abspath())
            args.append(self.outputs[0].abspath())
            call(args)

    src = bld.path
    out = bld.path.get_bld()

    efi = make_efi(env=bld.env)
    efi.set_inputs([out.make_node("boot.elf")])
    efi.set_outputs([out.make_node("boot.efi")])
    bld.add_to_group(efi)


# vim: ft=python et sw=4
