#! /usr/bin/env python
# encoding: utf-8

def options(opt):
	grp = opt.add_option_group('mbedTLS options')
	grp.add_option('--disable-mbedtls', action='store_false', dest='MBEDTLS', default=True,
		help='disable bundled mbedTLS and built-in HTTPS support [default: enabled]')

def configure(conf):
	conf.env.MBEDTLS = conf.options.MBEDTLS
	if not conf.env.MBEDTLS:
		return

	if not conf.path.find_dir('mbedtls') or not conf.path.find_dir('mbedtls/library'):
		conf.fatal('Can\'t find mbedtls submodule. Run `git submodule update --init --recursive`.')

	if not conf.path.find_dir('mbedtls/tf-psa-crypto/core'):
		conf.fatal('mbedTLS nested submodule tf-psa-crypto is missing. Run `git submodule update --init --recursive`.')

def build(bld):
	if not bld.env.MBEDTLS:
		return

	sources = bld.path.ant_glob([
		'mbedtls/library/*.c',
		'mbedtls/tf-psa-crypto/core/*.c',
		'mbedtls/tf-psa-crypto/extras/*.c',
		'mbedtls/tf-psa-crypto/platform/*.c',
		'mbedtls/tf-psa-crypto/utilities/*.c',
		'mbedtls/tf-psa-crypto/drivers/builtin/src/*.c',
	])

	sources += ['compat.c']

	defines = [
		'MBEDTLS_USER_CONFIG_FILE="xash_mbedtls_config.h"',
		'TF_PSA_CRYPTO_USER_CONFIG_FILE="xash_psa_config.h"',
	]

	includes = [
		'.',
		'mbedtls/include',
		'mbedtls/library',
		'mbedtls/tf-psa-crypto/include',
		'mbedtls/tf-psa-crypto/drivers/builtin/include',
		'mbedtls/tf-psa-crypto/core',
		'mbedtls/tf-psa-crypto/drivers/builtin/src',
		'mbedtls/tf-psa-crypto/utilities',
		'mbedtls/tf-psa-crypto/extras',
		'mbedtls/tf-psa-crypto/platform',
		'mbedtls/tf-psa-crypto/dispatch',
	]

	bld.stlib(
		source = sources,
		target = 'mbedtls',
		features = 'c',
		includes = includes,
		defines = defines,
		export_defines = ['XASH_MBEDTLS'],
		export_includes = [
			'.',
			'mbedtls/include',
			'mbedtls/tf-psa-crypto/include',
			'mbedtls/tf-psa-crypto/drivers/builtin/include',
		]
	)
