'Finds the .mobileprovision file to use for signing the bundle.
Checks all the installed provisioning profiles (or if the user specified
the PROVISIONING_PROFILE variable, only consult it) and select the most
specific that correspond to the bundle identifier.
Args:
profile: string, optional, short name of the .mobileprovision file
to use, if empty or the file is missing, the best file installed
will be used
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
Returns:
A tuple of the path to the selected provisioning profile, the data of
the embedded plist in the provisioning profile and the team identifier
to use for code signing.
Raises:
SystemExit: if no .mobileprovision can be used to sign the bundle.'

def _FindProvisioningProfile(self, profile, bundle_identifier):

    profiles_dir = os.path.join(os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning    Profiles')
    if (not os.path.isdir(profiles_dir)):
        print >>sys.stderr, ('cannot    find    mobile    provisioning    for    %s' % bundle_identifier)
        sys.exit(1)
    provisioning_profiles = None
    if profile:
        profile_path = os.path.join(profiles_dir, (profile + '.mobileprovision'))
        if os.path.exists(profile_path):
            provisioning_profiles = [profile_path]
    if (not provisioning_profiles):
        provisioning_profiles = glob.glob(os.path.join(profiles_dir, '*.mobileprovision'))
    valid_provisioning_profiles = {}
    for profile_path in provisioning_profiles:
        profile_data = self._LoadProvisioningProfile(profile_path)
        app_id_pattern = profile_data.get('Entitlements', {}).get('application-identifier', '')
        for team_identifier in profile_data.get('TeamIdentifier', []):
            app_id = ('%s.%s' % (team_identifier, bundle_identifier))
            if fnmatch.fnmatch(app_id, app_id_pattern):
                valid_provisioning_profiles[app_id_pattern] = (profile_path, profile_data, team_identifier)
    if (not valid_provisioning_profiles):
        print >>sys.stderr, ('cannot    find    mobile    provisioning    for    %s' % bundle_identifier)
        sys.exit(1)
    selected_key = max(valid_provisioning_profiles, key=(lambda v: len(v)))
    return valid_provisioning_profiles[selected_key]
