import os
import subprocess
Import('env')

env = env.Clone()
linkerscript = env.File('Arch/$ARCH/linker.ld')
env.Append(
    LINKSCRIPT=linkerscript,
    CXXFLAGS=[
        '-fanalyzer',
    ],
    LINKFLAGS=[
        '-T${LINKSCRIPT}',
    ],
)

crti = env.File('./Arch/$ARCH/Assembly/crti.s')
crtn = env.File('./Arch/$ARCH/Assembly/crtn.s')
# Toolchain should supply crtbegin and crtend
crtbegin = subprocess.check_output(
    [env.subst('$CC'), '-print-file-name=crtbegin.o']
).decode().rstrip()
crtend = subprocess.check_output(
    [env.subst('$CC'), '-print-file-name=crtend.o']
).decode().rstrip()

# All source file extensions used by the kernel
extensions = [
    '.c',
    '.cpp',
    '.s',
]

# Exclude crti.s and crtn.s from the glob since those are special
arch_sources = env.RecursiveGlob(root='./Arch/$ARCH', extensions=extensions, ignored_files=['crti.s', 'crtn.s'])
common_sources = env.RecursiveGlob(root='.', extensions=extensions, ignored_dirs=['./Arch'])

kernel = env.Program(
    'kernel',
    Flatten([
        # crti, crtbegin, crtend, and crtn must be
        # in this order or things will break!
        crti,
        crtbegin,
        arch_sources,
        common_sources,
        crtend,
        crtn,
    ]),
    LIBS=[
        'gcc',
        'alloc'
    ],
)

env.Depends(kernel, linkerscript)

Return('kernel')
