1#!/usr/bin/env python2.7
2#
3# Copyright 2017 Google Inc.
4#
5# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8import glob
9import os
10import re
11import shutil
12import subprocess
13import sys
14import tempfile
15
16# Arguments to the script:
17#  pkg              path to application directory, e.g. out/Debug/dm.app
18#                   executable and plist should already be in this directory
19#  identstr         search string (regex fragment) for code signing identity
20#  profile          name of provisioning profile
21pkg,identstr,profile = sys.argv[1:]
22
23# Find the Google signing identity.
24identity = None
25for line in subprocess.check_output(['security', 'find-identity']).split('\n'):
26  m = re.match(r'''.*\) (.*) "''' + identstr + '"', line)
27  if m:
28    identity = m.group(1)
29assert identity
30
31# Find the Google mobile provisioning profile.
32mobileprovision = None
33for p in glob.glob(os.path.join(os.environ['HOME'], 'Library', 'MobileDevice',
34                                'Provisioning Profiles', '*.mobileprovision')):
35  if re.search(r'''<key>Name</key>
36\t<string>''' + profile + r'''</string>''', open(p).read(), re.MULTILINE):
37    mobileprovision = p
38assert mobileprovision
39
40# The .mobileprovision just gets copied into the package.
41shutil.copy(mobileprovision,
42            os.path.join(pkg, 'embedded.mobileprovision'))
43
44# Extract the appliciation identitifer prefix from the .mobileprovision.
45m = re.search(r'''<key>ApplicationIdentifierPrefix</key>
46\t<array>
47\t<string>(.*)</string>''', open(mobileprovision).read(), re.MULTILINE)
48prefix = m.group(1)
49
50app, _ = os.path.splitext(os.path.basename(pkg))
51
52# Write a minimal entitlements file, then codesign.
53with tempfile.NamedTemporaryFile() as f:
54  f.write('''
55<plist version="1.0">
56  <dict>
57    <key>application-identifier</key> <string>{prefix}.com.google.{app}</string>
58    <key>get-task-allow</key>         <true/>
59  </dict>
60</plist>
61'''.format(prefix=prefix, app=app))
62  f.flush()
63
64  subprocess.check_call(['codesign',
65                         '--force',
66                         '--sign', identity,
67                         '--entitlements', f.name,
68                         '--timestamp=none',
69                         pkg])
70