#
# Copyright (C) 2007 Bahadir Balban
#

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

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

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


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

arch, subarch, plat = extract_arch_subarch_plat(config_h)

headers = ["#include/posix", l4lib_headers, kernel_headers]

env.Append(CPPPATH = headers)

src = glob.glob("src/*.c") + glob.glob("*.c")

libposix = env.StaticLibrary('posix', src)


