#
# Copyright (C) 2007 Bahadir Balban
#

import os
import glob
import sys
from os.path import join
from string import split

# libposix paths:
libposix_libpath = "../libposix"
libposix_incpath = "../libposix/include/posix"

project_root = "../.."
kernel_headers = join(project_root, "include")
config_h = join(project_root, "include/l4/config.h")

env = Environment(CC = 'arm-none-linux-gnueabi-gcc',
		  CCFLAGS = ['-g', '-nostdlib', '-ffreestanding'],
		  LINKFLAGS = ['-nostdlib'],
		  ASFLAGS = ['-D__ASSEMBLY__'],
		  ENV = {'PATH' : os.environ['PATH']},
		  LIBS = 'gcc',
		  CPPPATH = ['#include', libposix_incpath])


def extract_arch_subarch_plat(config_header):
	'''
	From the autogenerated kernel config.h, extracts platform, archictecture,
	subarchitecture information. This is used to include the relevant headers
	from the kernel directories.
	'''
	arch = None
	subarch = None
	plat = None

	if not os.path.exists(config_header):
		print "\n\nconfig.h does not exist. "\
		      "Please run: `scons configure' first\n\n"
		sys.exit()
	f = open(config_h, "r")
	while True:
		line = f.readline()
		if line == "":
			break
		parts = split(line)
		if len(parts) > 0:
			if parts[0] == "#define":
				if parts[1] == "__ARCH__":
					arch = parts[2]
			   	elif parts[1] == "__PLATFORM__":
					plat = parts[2]
			   	elif parts[1] == "__SUBARCH__":
					subarch = parts[2]
	f.close()
	if arch == None:
		print "Error: No config symbol found for architecture"
		sys.exit()
	if subarch == None:
		print "Error: No config symbol found for subarchitecture"
		sys.exit()
	if plat == None:
		print "Error: No config symbol found for platform"
		sys.exit()
	return arch, subarch, plat

def create_symlinks(arch):
	if not os.path.exists("include/l4lib/arch"):
		os.system("ln -s %s %s" % ("arch-" + arch, "include/l4lib/arch"))

arch, subarch, plat = extract_arch_subarch_plat(config_h)

create_symlinks(arch) # Creates symlinks to architecture specific directories.

headers = ["#include", "#include/libl4/arch", kernel_headers]

env.Append(CPPPATH = headers)

src = glob.glob("src/*.c") + glob.glob("src/%s/*.[cS]" % arch)

libl4 = env.StaticLibrary('l4', src)


