#!/usr/bin/python

import sys

#This script is based on the PostProcessBuildPlayer provided by Qualcomm's Vuforia plugin

# Processes the given xcode project to add or change the supplied parameters
#   xcodeproj_filename - filename of the Xcode project to change
#   frameworks - list of Apple standard frameworks to add to the project
#   resfiles - list resource files added to the project
def process_pbxproj(xcodeproj_filename):

	# Open up the file generated by Unity and read into memory as
	# a list of lines for processing
	pbxproj_filename = xcodeproj_filename + '/project.pbxproj'
	pbxproj = open(pbxproj_filename, 'r')
	lines = pbxproj.readlines()
	pbxproj.close()


	# Next open up an empty project.pbxproj for writing and iterate over the old
	# file copying the original file and inserting anything extra we need
	pbxproj = open(pbxproj_filename, 'w')
	subsection = ''
	stage = 0

	i = 0
	for i in range(0, len(lines)):
		line = lines[i]

		#if there is already an entry for our setting, don't copy it - we'll create our own
		#and don't bother further parsing that line
		if line.find('DEBUG_INFORMATION_FORMAT') < 0:
			pbxproj.write(line)

			# Each section starts with a comment such as
			# /* Begin Section_Name section */'
			if stage == 0:
				if line.find('/* Begin XCBuildConfiguration section */') >= 0:
					stage = 1

			#inside the 'XCBuildConfiguration' section    
			elif stage == 1:
				if line.find('/* Debug */ = {') >= 0:
					subsection = 'Debug'
					stage = 2
				elif line.find('/* Release */ = {') >= 0: 
					subsection = 'Release'
					stage = 2

			elif stage == 2:
				if line.find('buildSettings = {') >= 0:
					if subsection == 'Debug':
						print('set debug format')
						#we want to set this option to dwarf for debug
						pbxproj.write('\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n')
						stage = 1
					elif subsection == 'Release':
						print('set release format')
						#and generate the dsym for release as it's required for symbolication of crash reports
						pbxproj.write('\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf-with-dsym;\n')
						stage = 1
			

	pbxproj.close()



# Script start
print "Starting PostProcessBuildPlayer with the following arguments..."

i = 0
for args in sys.argv:
	print str(i) +': ' + args
	i += 1

# Check this is an iOS build before running
if sys.argv[2] == "iPhone":
	xcodeproj_full_path_name = sys.argv[1] + '/Unity-iPhone.xcodeproj'
	process_pbxproj(xcodeproj_full_path_name)