##
# This script includes generic build options:
#    release/debug, target os, target arch, cross toolchain, build environment etc
##
import os
import platform

# Map of host os and allowed target os (host: allowed target os)
host_target_map = {
		'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
		'windows': ['windows', 'winrt', 'android', 'arduino'],
		'darwin': ['darwin', 'ios', 'android', 'arduino'],
		}

# Map of os and allowed archs (os: allowed archs)
os_arch_map = {
		'linux': ['x86', 'x86_64', 'arm', 'arm64'],
		'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
		'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
		'windows': ['x86', 'amd64', 'arm'],
		'winrt': ['arm'],
		'darwin': ['i386', 'x86_64'],
		'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
		'arduino': ['avr', 'arm'],
                'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
		}

es_role_map = {
		'enrollee', 'mediator'
		}

es_target_enrollee_map = {
		'arduino', 'tizen', 'linux'
		}

es_softap_mode_map = {
		'ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP'
		}

host = platform.system().lower()

if not host_target_map.has_key(host):
	print "\nError: Current system (%s) isn't supported\n" % host
	Exit(1)

######################################################################
# Get build options (the optins from command line)
######################################################################
target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os

if target_os not in host_target_map[host]:
	print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
	Exit(1)

default_arch = platform.machine()
if default_arch not in os_arch_map[target_os]:
	default_arch = os_arch_map[target_os][0].lower()

target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch

# True if binary needs to be installed on board. (Might need root permissions)
# set to 'no', 'false' or 0 for only compilation
require_upload = ARGUMENTS.get('UPLOAD', True)

# Get the device name
device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")

# Get es_role
es_role = ARGUMENTS.get('ES_ROLE')

if es_role not in es_role_map:
	print "\nError: Unknown ES_ROLE: %s (Allow values: %s)\n" % (es_role, es_role_map)
	Exit(1)

# Get es_target_enrollee
es_target_enrollee = ARGUMENTS.get('ES_TARGET_ENROLLEE')

if es_target_enrollee not in es_target_enrollee_map:
	print "\nError: Unknown ES_TARGET_ENROLLEE: %s (Allow values: %s)\n" % (es_target_enrollee, es_target_enrollee_map)
	Exit(1)

# Get es_soft_mode
es_soft_mode = ARGUMENTS.get('ES_SOFTAP_MODE')

if es_soft_mode not in es_softap_mode_map:
	print "\nError: Unknown ES_SOFTAP_MODE: %s (Allow values: %s)\n" % (es_soft_mode, es_softap_mode_map)
	Exit(1)

######################################################################
# Common build options (release, target os, target arch)
######################################################################
help_vars = Variables()
help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False))
help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'TCP']))
help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))

help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)

#ES_TARGET_ENROLLEE is for specifying what is our target enrollee (Arduino or rest of platforms which support Multicast)
help_vars.Add(EnumVariable('ES_TARGET_ENROLLEE', 'Target Enrollee', 'arduino', allowed_values=('arduino', 'tizen', 'linux')))
#ES_ROLE is for specifying the role (Enrollee or Mediator) for which scons is being executed
help_vars.Add(EnumVariable('ES_ROLE', 'Target build mode', 'mediator', allowed_values=('mediator', 'enrollee')))
#ES_SOFT_MODE is for specifying MODE (Mode 1 : Enrollee with  Soft AP or Mode 2  : Mediator with Soft AP)
help_vars.Add(EnumVariable('ES_SOFTAP_MODE', 'Target build mode', 'ENROLLEE_SOFTAP', allowed_values=('ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP')))

AddOption('--prefix',
                  dest='prefix',
                  type='string',
                  nargs=1,
                  action='store',
                  metavar='DIR',
                  help='installation prefix')

######################################################################
# Platform(build target) specific options: SDK/NDK & toolchain
######################################################################
targets_support_cc = ['linux', 'arduino', 'tizen']

if target_os in targets_support_cc:
	# Set cross compile toolchain
	help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
	help_vars.Add(PathVariable('TC_PATH',
			'Toolchain path (Generally only be required for cross-compiling)',
			os.environ.get('TC_PATH')))

if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
	env = Environment(variables = help_vars,
			tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
			)
else:
	env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, ES_ROLE = es_role, ES_TARGET_ENROLLEE = es_target_enrollee, ES_SOFTAP_MODE = es_soft_mode, ESPREFIX = GetOption('prefix'))

Help(help_vars.GenerateHelpText(env))

# Set device name to __OIC_DEVICE_NAME__
env.AppendUnique(CPPDEFINES = ['-D__OIC_DEVICE_NAME__=' + "\'\"" + device_name + "\"\'"])

tc_set_msg = '''
************************************ Warning **********************************
*   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
* toolchain, if it isn't what you expect you should unset it, otherwise it may*
* cause inexplicable errors.                                                  *
*******************************************************************************
'''

if target_os in targets_support_cc:
	prefix = env.get('TC_PREFIX')
	tc_path = env.get('TC_PATH')
	if prefix:
		env.Replace(CC = prefix + 'gcc')
		env.Replace(CXX = prefix + 'g++')
		env.Replace(AR = prefix + 'ar')
		env.Replace(AS = prefix + 'as')
		env.Replace(LINK = prefix + 'ld')
		env.Replace(RANLIB = prefix + 'ranlib')

	if tc_path:
		env.PrependENVPath('PATH', tc_path)
		sys_root = os.path.abspath(tc_path + '/../')
		env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
		env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])

	if prefix or tc_path:
		print tc_set_msg

# Ensure scons be able to change its working directory
env.SConscriptChdir(1)

# Set the source directory and build directory
#   Source directory: 'dir'
#   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
#
# You can get the directory as following:
#   env.get('SRC_DIR')
#   env.get('BUILD_DIR')

def __set_dir(env, dir):
	if not os.path.exists(dir + '/SConstruct'):
		print '''
*************************************** Error *********************************
* The directory(%s) seems isn't a source code directory, no SConstruct file is
* found. *
*******************************************************************************
''' % dir
		Exit(1)

	if env.get('RELEASE'):
		build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
	else:
		build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
	env.VariantDir(build_dir, dir, duplicate=0)

	env.Replace(BUILD_DIR = build_dir)
	env.Replace(SRC_DIR = dir)

def __src_to_obj(env, src, home = ''):
	obj = env.get('BUILD_DIR') + src.replace(home, '')
	if env.get('OBJSUFFIX'):
		obj += env.get('OBJSUFFIX')
	return env.Object(obj, src)

def __install(ienv, targets, name):
	i_n = ienv.Install(env.get('BUILD_DIR'), targets)
	Alias(name, i_n)
	env.AppendUnique(TS = [name])

def __installlib(ienv, targets, name):
	user_prefix = env.get('PREFIX')
	if user_prefix:
		i_n = ienv.Install(user_prefix + '/lib', targets)
	else:
		i_n = ienv.Install(env.get('BUILD_DIR'), targets)
	ienv.Alias("install", i_n)

def __installbin(ienv, targets, name):
	user_prefix = env.get('PREFIX')
	if user_prefix:
		i_n = ienv.Install(user_prefix + '/bin', targets)
	else:
		i_n = ienv.Install(env.get('BUILD_DIR'), targets)
	ienv.Alias("install", i_n)

def __append_target(ienv, target):
	env.AppendUnique(TS = [target])

def __print_targets(env):
	Help('''
===============================================================================
Targets:\n    ''')
	for t in env.get('TS'):
		Help(t + ' ')
	Help('''
\nDefault all targets will be built. You can specify the target to build:

    $ scons [options] [target]
===============================================================================
''')

env.AddMethod(__set_dir, 'SetDir')
env.AddMethod(__print_targets, 'PrintTargets')
env.AddMethod(__src_to_obj, 'SrcToObj')
env.AddMethod(__append_target, 'AppendTarget')
env.AddMethod(__install, 'InstallTarget')
env.AddMethod(__installlib, 'UserInstallTargetLib')
env.AddMethod(__installbin, 'UserInstallTargetBin')
env.SetDir(env.GetLaunchDir())
env['ROOT_DIR']=env.GetLaunchDir()+'/..'

Export('env')

# Delete the temp files of configuration
if env.GetOption('clean'):
	dir = env.get('SRC_DIR')

	if os.path.exists(dir + '/config.log'):
		Execute(Delete(dir + '/config.log'))
		Execute(Delete(dir + '/.sconsign.dblite'))
		Execute(Delete(dir + '/.sconf_temp'))

Return('env')
