######################################################################
# ref. raxmpp library build script
#
######################################################################
import os
import commands

Import('env')

base_dir = env.get('SRC_DIR')
target_os = env.get('TARGET_OS')
target_arch = env.get('TARGET_ARCH')
build_path = Dir('.').abspath

with_ra_ibb = env.get('WITH_RA_IBB')
PKG_NAME = 'strophe'
SRC_NAME = 'libstrophe'
EXT_NAME = 'libstrophe'
EXT_BASE = 'extlibs/' + EXT_NAME
EXT_PATH = EXT_BASE + '/' + SRC_NAME
SRC_PATH = base_dir + '/' + EXT_PATH
INC_PATH = SRC_PATH
LIB_PATH = SRC_PATH + '/' + '.libs'

if with_ra_ibb:
	# check 'libstrophe' library, if it doesn't exits, ask user to download it
	if not os.path.exists(SRC_NAME):
		raxmpp_env = Environment(ENV = os.environ)
		c = raxmpp_env.Action(['git clone https://github.com/strophe/libstrophe.git ' + SRC_NAME,
			'cd ' + SRC_NAME + ' && git checkout 527bc0573a52f2af3ecad5b9ef39aeec7b669f77'
			])

		print 'Downloading xmpp library ...'
		if raxmpp_env.Execute(c):
			print '''
	*********************************** Error: ***********************************************
	* Please download ra_xmpp as following:
	*     $ git clone https://github.com/strophe/libstrophe.git extlibs/libstrophe/libstrophe
	*     $ cd  extlibs/libstrophe/libstrophe
	*     $ git checkout 527bc0573a52f2af3ecad5b9ef39aeec7b669f77
	******************************************************************************************
	'''
			Exit(1)
		else:
			print 'Download xmpp library complete'

	print 'Building with ' + SRC_NAME
	#print 'base_dir', base_dir
	#print 'target_os', target_os
	#print 'target_arch', target_arch

	foo=commands.getoutput('patch -N -p1 -d libstrophe < strophe-xmpp_conn_is_secured.patch')
	print foo

	os.chdir(SRC_NAME)
	#sconsflags = ' RELEASE=true' if  env['RELEASE'] else ' RELEASE=false'
	if not os.path.exists('configure') :
		foo=commands.getoutput('./bootstrap.sh')
		print foo
	if not os.path.exists('config.status') :
		foo=commands.getoutput('./configure')
		print foo
	if not os.path.exists('.libs/libstrophe.a') :
		foo=commands.getoutput('make libstrophe.la')
		print foo
	if not os.path.exists('.libs/libstrophe.a') :
		print 'Building with ' + SRC_NAME + ' failed.'
		Exit(2)

	print 'Building with ' + SRC_NAME + ' Completely.'
	env.AppendUnique(CPPPATH = [INC_PATH], RALIBS = ['strophe', 'ssl', 'crypto', 'resolv'], RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])

if env.GetOption('clean') :
	act = env.Action(['cd ' + SRC_PATH, 'make clean'])
	env.Execute(act)
