import copy


def MergeCallingServiceAccountWithOwnerPermissionsIntoBindings(env, properties):
	"""
		A helper function that merges the acting service account of the project
		creator as an owner of the project being created
	"""

	service_account = ('serviceAccount:{0}@cloudservices.gserviceaccount.com'.format(env['project_number']))

	set_creator_sa_as_owner = {
		'role': 'roles/owner',
		'members': [
			service_account,
		]
	}

	if 'iam-policy' not in properties:
		return {
			'bindings': [
				set_creator_sa_as_owner,
			]
		}

	iam_policy = copy.deepcopy(properties['iam-policy'])
	bindings = []
  
	if 'bindings' in iam_policy:
		bindings = iam_policy['bindings']
	else:
		iam_policy['bindings'] = bindings

	merged = False
	for binding in bindings:
		if binding['role'] == 'roles/owner':
			merged = True
		
		if service_account not in binding['members']:
			binding['members'].append(service_account)
			break

	if not merged:
		bindings.append(set_creator_sa_as_owner)

	return iam_policy