Import("*")
import os
import glob
from os.path import join

arch = 'arm'
clibvariant = 'baremetal'
# C library information
clibroot = join(os.getcwd(), '../libs/c')
clibpath = join(join(clibroot, 'build'), clibvariant)
cincpath = [join(clibroot, 'include'), join(clibroot,'include/arch/%s' % arch)]
crt0objpath = join(clibroot, 'build/crt/sys-%s/arch-%s/crt0.o' % (clibvariant, arch))
clibname = "c-" + clibvariant

# Elf library information
elflibpath = os.getcwd() + '/../libs/elf'
elfincpath = [elflibpath + '/include']

env = Environment(CC = 'arm-none-linux-gnueabi-gcc',
		  CCFLAGS = ['-g', '-nostdlib', '-ffreestanding'],
		  LINKFLAGS = ['-nostdlib', '-Tmylink.lds'],
		  ENV = {'PATH' : os.environ['PATH']},
		  PROGSUFFIX = '.axf',
		  LIBS = ['elf', clibname, 'gcc', clibname], # Note there's a dependency order here.
		  						# Left libs depend on libs on their right.
		  CPPPATH = ['#'] + cincpath + elfincpath)

env.Append(LIBPATH = [clibpath, elflibpath])

def src_glob(search):
    """Src glob is used to find source files easily e.g: src_glob("src/*.c"),
    the reason we can't just use glob is due to the way SCons handles out
    of directory builds."""
    dir = os.path.dirname(search)
    if dir != "":
        dir = dir + os.sep
    src_path = Dir('.').srcnode().abspath
    files = glob.glob(src_path + os.sep + search)
    files = map(os.path.basename, files)
    ret_files = []
    for file in files:
        ret_files.append(dir + file)
    return ret_files

src = src_glob("*.c")
src += src_glob("*.S")

obj_list = env.Object(src)
loader = env.Program("final", obj_list + [crt0objpath])


