#!/usr/bin/env python
#
# Scons script for building the iphone library
#
import os,platform,sys,urllib,gzip,glob
from progressbar import ProgressBar

ticore_version = '9'

# NOTE: this is simply a pre-built version of the source at http://github.com/appcelerator/tijscore
# since this is so freaking complicated to setup and build in an stable environment, and since 
# it takes like an hour to build the library, we have, as a convenience, pre-built it from the
# exact same source and are providing the pre-compiled versions for i386/arm
libname = 'libTiCore-%s.a' % ticore_version
thirdparty_name = '%s.gz' % libname
libfile = 'lib/%s' % libname
outfile = 'lib/libTiCore.a'
markerfile = 'lib/%s.txt' % ticore_version
url = 'http://timobile.appcelerator.com.s3.amazonaws.com/%s' % (thirdparty_name)

try:
	# pull in the version from the top-level SConstruct
	Import('version')
except:
	if ARGUMENTS.get('PRODUCT_VERSION', 0):
		version = ARGUMENTS['PRODUCT_VERSION']
	else:
		version = '0.0.0'

defines='TI_VERSION=%s ' % version

config = 'Release'

flags = ''

if ARGUMENTS.get('COMPILER_FLAGS', 0):
	flags = ARGUMENTS.get('COMPILER_FLAGS')

build_type = ARGUMENTS.get("BUILD_TYPE", None)
iphone_dir = os.path.abspath(os.path.join(os.path.dirname(sys._getframe(0).f_code.co_filename),'../','support','iphone'))
sys.path.append(iphone_dir)

import run,prereq

def fetch():
	print "You don't seem to have the appropriate thirdparty files. I'll fetch them."
	print "This could take awhile.. Might want to grab a cup of Joe or make fun of Nolan."
	print "Downloading %s" % url

	# delete all the old marker files so we can rollback
	for f in glob.glob('lib/*.txt'):
		os.remove(f)
	
	pbar = ProgressBar().start()
	try:
		def progress_callback(count, block_size, total_size):
			if (total_size < 0):
				raise Exception("Could not fetch archive! Does it exist on the server?")
			percent = int(count * block_size * 100/total_size)
			pbar.update(percent)
 
		fname, msg = urllib.urlretrieve(url, reporthook=progress_callback)
 
		print "Fetched it (%s). I'm going to unpack it now..." % (fname)
		
		if not os.path.exists('lib'):
			os.makedirs('lib')
		
		ofile = open(outfile,'wb')
		gfile = gzip.open(fname,'rb')
		ofile.write(gfile.read())
		ofile.close()
		gfile.close()
		
		mfile = open(markerfile,'w')
		mfile.write('DO NOT DELETE THIS FILE.')
		mfile.close()
		
	finally:
		urllib.urlcleanup()
		pbar.finish()

def build_titanium_target(name,apiversion,targetversion,target):
	# execute the phone and simulator release builds
	build_extras = "IPHONEOS_DEPLOYMENT_TARGET=%s TARGETED_DEVICE_FAMILY='iPhone/iPad'" % targetversion
	output = -1
	if os.path.exists('/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS%s.sdk' % apiversion):
		output = os.system("xcodebuild -sdk iphoneos%s -project Titanium.xcodeproj -target %s -configuration %s GCC_PREPROCESSOR_DEFINITIONS='%s %s' %s %s" % (apiversion,name,config,defines,flags,build_extras,target))
	if output!=0:
		sys.exit(output)

	if os.path.exists('/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator%s.sdk' % apiversion):
		output = os.system("xcodebuild -sdk iphonesimulator%s -project Titanium.xcodeproj -target %s -configuration %s GCC_PREPROCESSOR_DEFINITIONS='DEBUG=1 %s %s' %s %s" % (apiversion,name,config,defines,flags,build_extras,target))

	if output!=0:
		sys.exit(-1)

def clean(dir,name,apiversion,targetversion):
	curdir = os.path.abspath(os.curdir)
	if not os.path.exists(dir): return

	os.chdir(dir)

	build_titanium_target(name,apiversion,targetversion,"clean")
	
	os.chdir(curdir)

def build(apiversion,targetversion,name,target,namever=''):
	curdir = os.path.abspath(os.curdir)
	os.chdir('iphone')

	build_titanium_target(target,apiversion,targetversion,"build")
	
	os.chdir(curdir)

if not os.path.exists(markerfile) or len(glob.glob('lib/*.txt')) > 1:
	fetch()


sys.exit(0)
